Iphone 使用nsrunlop
我正在viewDidLoad中运行2个方法,在它们之间运行nsrunlop 10秒Iphone 使用nsrunlop,iphone,objective-c,xcode,nsrunloop,Iphone,Objective C,Xcode,Nsrunloop,我正在viewDidLoad中运行2个方法,在它们之间运行nsrunlop 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
-(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秒后我只看到[恐怖]的结果。另一方面,当我仅在视图中保留[nextImage]并加载图像更改时,我认为nsrunlop出现问题,您不应该在大多数时间直接使用运行循环。方法
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(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;
}
...
当您需要取消时:
...
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 ...
}