问题
I have function call loop, but I want call it if my view appears, and not call it when the view disappears.
Loop Function :
-(void)updateArray
{
while (1)
{
NSLog(@"IN LOOP");
[NSThread sleepForTimeInterval:2.0];
if([FileSizeArray count] >0 || [FileCurrentSizeArray count] >0)
{
[FileSizeArray removeObjectsInRange:NSMakeRange(1, FileSizeArray.count-1)];
[FileCurrentSizeArray removeObjectsInRange:NSMakeRange(1, FileSizeArray.count-1)];
}
[FileNameArray removeAllObjects];
[UserNameArray removeAllObjects];
...
}
And in ViewWillAppear()
timer= [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(updateArray:)
userInfo: nil repeats:NO];
And in DidDisAppear()
[timer invalidate];
timer = nil;
But it not working, it still call and my app has crash.
Can anyone help me? Thanks in advance
回答1:
It sounds to me that what you really want to do is use Key-Value Observing to receive a callback when FileSizeArray
and FileCurrentSizeArray
change.
In ViewDidAppear
:
[self addObserver:self forKeyPath:@"FileSizeArray.count" options: 0 context: nil];
[self addObserver:self forKeyPath:@"FileCurrentSizeArray.count" options: 0 context: nil];
Callback:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"FileSizeArray.count"]) {
//do something
} else if ([keyPath isEqualToString:@"FileCurrentSizeArray.count"]) {
//do something
}
}
remember to unregister:
[self removeObserver:self forKeyPath:@"FileSizeArray"];
[self removeObserver:self forKeyPath:@"FileCurrentSizeArray"];
来源:https://stackoverflow.com/questions/17438987/stop-nsthread-on-ios