首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSRunLoop

使用NSRunLoop
EN

Stack Overflow用户
提问于 2011-12-27 17:21:39
回答 1查看 793关注 0票数 0

我在viewDidLoad中运行了两个方法,在这两个方法之间,我运行了10秒的NSRunLoop

代码语言:javascript
复制
-(void)nextImage{ //charging a random image in the image view

    index = [[NSArray alloc]initWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",nil];
    NSUInteger randomIndex = arc4random() % [index count];
    NSString *imageName = [index objectAtIndex:randomIndex];
    NSLog(@"%@",imageName);
    self.banner=[UIImage imageNamed:imageName];
    self.imageView.image=banner;
    [imageName release];
}

-(void)horror{

    self.banner=[UIImage imageNamed:@"Flo.jpg"];
    self.imageView.image=banner;
    NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/scream.wav"];
    SystemSoundID soundID;
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

- (void)viewDidLoad
{

    [self nextImage];

    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10.0]];

    [self horror];

    [super viewDidLoad];
}

这里的图像没有改变,黑屏,10秒后我只看到了恐怖的结果。另一方面,当我在viewDidLoad中只保留nextImage图像时,我认为我的NSRunLoop出了问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-12-27 17:51:20

在大多数情况下,您不应该直接使用run循环。方法runUntilDate:不做你认为它能做的事情。对于您的用例,您应该设置一个计时器:

代码语言:javascript
复制
- (void)viewDidLoad
{
    [self nextImage];
    [NSTimer scheduledTimerWithTimeInterval: 10.0 target: self selector: @selector(horror) userInfo: nil repeats: NO];
    [super viewDidLoad];
}

计时器将在10秒后触发(timeInterval: 10.0),然后使目标对象(本例中是您的视图控制器,由于target: self)执行方法horror (由于selector: @selector(horror))。

如果有任何机会,你的视图控制器可能会在时间过去之前变得不活动,保护ivar中的timer实例,并取消它:

代码语言:javascript
复制
...
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval: 10.0 target: self selector: @selector(horror) userInfo: nil repeats: NO];
self.myTimerProperty = timer;
...

当你需要取消它的时候:

代码语言:javascript
复制
...
if (self.myTimerProperty)
{
    // Ok. Since we have a timer here, we must assume, that we have set it
    // up but it did not fire until now. So, cancel it 
    [self.myTimerProperty invalidate];
    self.myTimerProperty = nil;
}
...

顺便说一句,如果你这样做,从回调方法中清除timer属性可能是个好主意:

代码语言:javascript
复制
- (void) horror
{
    self.myTimerProperty = nil;
    ... other horrible stuff ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8642945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档