0

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

Girish
  • 4,692
  • 4
  • 35
  • 55
  • Can you add the error message you received when the app crashed and on which line it crashed? Also `scheduledTimerWithTimeInterval...` schedules the timer on current thread (which is the main one, since it's called from `viewWillAppear`), and you shouldn't call `[NSThread sleep...]` on main thread. – Khanh Nguyen Jul 03 '13 at 03:43
  • because your method doesn't have any paramters and though you are passing it, just change method name in timer to (updateArray) it will be fine. – Dipen Panchasara Jul 03 '13 at 04:05

2 Answers2

0

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"];
StaRbUck42
  • 117
  • 1
  • 8
0

[NSThread exit]; or [NSThread performSelector:@selector(exit) onThread:thread withObject:nil waitUntilDone:YES];

jack chao
  • 1
  • 1