我在viewDidLoad中运行了两个方法,在这两个方法之间,我运行了10秒的NSRunLoop
-(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出了问题
发布于 2011-12-27 17:51:20
在大多数情况下,您不应该直接使用run循环。方法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中的timer实例,并取消它:
...
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;
}
...顺便说一句,如果你这样做,从回调方法中清除timer属性可能是个好主意:
- (void) horror
{
self.myTimerProperty = nil;
... other horrible stuff ...
}https://stackoverflow.com/questions/8642945
复制相似问题