0

我在 viewDidLoad 中运行 2 个方法,在它们之间运行 NSRunLoop 10 秒

-(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 出了点问题

4

1 回答 1

1

大多数时候你不应该直接使用运行循环。该方法runUntilDate:没有,您认为它会做什么。对于您的用例,您应该设置一个计时器:

- (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 中,然后将其取消:

...
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval: 10.0 target: self selector: @selector(horror) userInfo: nil repeats: NO];
self.myTimerProperty = timer;
...

当您需要取消它时:

...
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;
}
...

顺便说一句,如果您这样做,最好从回调方法中清除计时器属性:

- (void) horror
{
    self.myTimerProperty = nil;
    ... other horrible stuff ...
}
于 2011-12-27T09:51:19.723 回答