<分区>
我想在 View 消失时停止调用循环函数。我怎样才能做到这一点?这是我的代码:
-(void) viewWillAppear:(BOOL)animated
{
[self performSelectorInBackground:@selector(updateArray) withObject:nil];
}
和:
-(void)updateArray
{
while (1)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
....}
updateArray 通常在这个 View 消失时被调用。我想停止调用 updateArray 函数
提前致谢
最佳答案
制作一个BOOL
iVar 或属性
BOOL loopShouldRun;
在 viewWillAppear 中将其设置为 YES
。
然后使用这段代码
-(void)updateArray
{
while (loopShouldRun)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
....}
}
并在 viewWillDisappear 中将其设置为 NO。
但是正如@Michael Deuterman 在评论中提到的那样,当 View 在 sleepTimer 触发之前消失时可能会出现问题。
所以这是另一个使用 NSTimer 的解决方案。
NSTimer
iVar/@property: @property (strong) NSTimer *timer;
在 viewWillAppear
中创建计时器:
timer = [NSTimer timerWithTimeInterval:2.0 invocation:@selector(updateArray) repeats:Yes]
在 viewWillDiappear
中使计时器无效:
if ([self.timer isValid]) {
[自拍无效]
}
您的 updateArray
现在应该如下所示:
-(void)updateArray {
NSLog(@"in loop");
}
关于iphone - IOS中如何停止调用循环功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17441798/
相关文章:
ios - 是否有必要为最新的 iOS 应用程序添加非视网膜图像
iphone - 当单元格滚出 View 时,TableViewCell 的 textLabel 值返回到 1
ios - 了解objc中 block 存储管理的一种极端情况
ios - 使用 NSRecursiveLock 从方法返回值
iphone - retain setter 是如何用@synthesize 实现的?
iphone - 请解释这可能是如何泄漏的 - 字符串编码函数
iphone - SecTrustCreateWithCertificates 在 iPad 上崩溃
ios - 在 AVPlayer 中切换视频会在更改时创建 Flash