I’m very new to Objective-C and I’m trying to develop an iPhone app. My problem is I get “message sent to deallocated instance 0x3d54830” error when I use an object inside an NSTimer. When I don’t use an NSTimer, I can use the object just fine. For example:
//These can be any objects. Le't say I have a Song class and a SongReader class in the header file SongTest.h
Song *song;
SongReader *reader;
NSTimer *timer;
- (void)justDoIt;
//In the implementation file SongTest.m
- (void)viewDidLoad {
reader = [[SongReader alloc] init];
song = [reader readSong];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(justDoIt) userInfo:nil repeats:YES];
}
- (void)justDoIt {
NSLog(@"This is a song integer property: %d", song.wordCount);
}
- (void)dealloc {
[reader release];
[super dealloc];
}
The song object inside the justDoIt method/selector/message is already deallocated according to the debugger. What am I doing wrong? Even if I do it like:
song = [[reader readSong] retain]; //or
[song retain]; //or
[reader retain];
The object still gets deallocated unexpectedly. Again, the problem only happens when I use NSTimer. It’s like the object gets deallocated even before the timer fires.
Are you retaining your SongTest object? You don’t show that part of the code, but if it’s autoreleased, it will be deallocated by the time the timer fires. In fact, that’s really what the error message is indicating:
You’re creating the timer to send a message to “self” which is the SongTest object.
Also, you do need to retain the song:
if you’ve coded -readSong according to the standard Cocoa conventions.