我想在查看disapear時停止呼叫循環功能。我怎樣才能做到這一點?這是我的代碼:如何在IOS中停止呼叫循環功能
-(void) viewWillAppear:(BOOL)animated
{
[self performSelectorInBackground:@selector(updateArray) withObject:nil];
}
而且:當這個視圖中消失
updateArray通常callled。我想停下來調用updateArray功能提前
感謝
我想在查看disapear時停止呼叫循環功能。我怎樣才能做到這一點?這是我的代碼:如何在IOS中停止呼叫循環功能
-(void) viewWillAppear:(BOOL)animated
{
[self performSelectorInBackground:@selector(updateArray) withObject:nil];
}
而且:當這個視圖中消失
updateArray通常callled。我想停下來調用updateArray功能提前
感謝
請在viewWillAppear中的BOOL
伊娃或財產
BOOL loopShouldRun;
將其設置爲YES
。
然後使用此代碼
-(void)updateArray
{
while (loopShouldRun)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
....}
}
和viewWillDisappear它設置爲NO。
但正如@Michael Deuterman在評論中提到的那樣,在sleepTimer激發之前視圖消失時可能會出現問題。
所以繼承人是NSTimer的另一個解決方案。在viewWillAppear
@property (strong) NSTimer *timer;
創建定時器:在viewWillDiappear
timer = [NSTimer timerWithTimeInterval:2.0 invocation:@selector(updateArray) repeats:Yes]
無效定時器:
NSTimer
伊娃/ @財產 if ([self.timer isValid]) { [self.timer invalidate] }
您updateArray
現在應該是這樣的:
-(void)updateArray {
NSLog(@"in loop");
}
這不是最佳答案。這個@Pfitz的問題在於,「sleepForTimeInterval:2.0'中的長時間睡眠時間返回前,視圖可能會消失並釋放。 –
timer = [NSTimer timerWithTimeInterval:2.0調用:@selector(updateArray)重複:是]它錯誤。它不起作用 –
while (1)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
}
而(1)將是真正的永恆。要停止它,你需要有一個條件來阻止循環的發生。
例如,
while (1)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
if(something happens)
break;
}
希望它可以幫助你。
或(!(發生的事情)){...} – zbMax
這是一個簡單的邏輯......只取標記變量和更新標誌varibale的價值,當你viewdisapper然後
- (void)viewWillDisappear:(BOOL)animated
上述方法方法將調用視圖中消失之前
viewDidDisappear:(BOOL)animated
上面的方法也存在。將被稱爲剛過你的看法也消失
所以你可以根據你的標誌變量值改變一個以上method.then你的標誌變量的值只是把break
在while循環,你的循環將打破 。的performSelector
NSThread *myThread; // preferable to declare in class category in .m file or in .h file
在viewWillAppear中
myThread = [[NSThread alloc] initWithTarget:self selector:@selector(updateArray) object:nil];
[myThread start];
在viewWillDisappear
[myThread cancel]; // This will stop the thread and method will get stopped from execution
myThread = nil; // Release and nil object as we are re-initializing in viewWillAppear
莫
你有清除你的問題嗎? –
這與你以前的問題有什麼不同http://stackoverflow.com/questions/17438987/stop-nsthread-on-ios? –
呃...你可以使用'break'來停止任何循環。 – TheTiger