Not much code here, but this problem is seriously annoying me!
.h:
@interface processController : UIViewController {
NSTimer *timer;
}
@property (nonatomic, retain) NSTimer *timer;
.m:
- (void)viewDidLoad {
[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector (main) userInfo:nil repeats:YES];
}
- (void)main {
NSLog(@"testing");
}
- (void)viewDidUnload {
[self.timer invalidate];
self.timer = nil;
}
The weird thing is, when I fire this code:
ViewController *main = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:main animated:YES];
and switch views, the timer keeps firing! What am I doing wrong?
viewDidUnloadis not called when the view is removed from the screen but only when a memory warning is received by the application. It’s not called when the UIViewController is deallocated either. From Apple’s documentation:You most likely meant to use
viewWillDisappearYou probably want to start your timer in the viewWillAppear: as viewDidLoad is called as soon as the controller’s view property is accessed. Not nercessarely when the view is shown.
I’d recommend reading the discussions for viewDidLoad and viewDidUnload as well as viewWillAppear and viewWillDisappear from the UIViewController documentation.