我對Objective-C非常陌生,我試圖開發一個iPhone應用程序。我的問題是當我在一個NSTimer中使用一個對象時,我得到了「消息發送到解除分配的實例0x3d54830」的錯誤。當我不使用NSTimer時,我可以很好地使用該對象。例如:Objective-C對象意外解除分配
//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];
}
的justDoIt方法/選擇/消息內的歌曲對象根據調試器已經釋放。我究竟做錯了什麼?即使我這樣做:
song = [[reader readSong] retain]; //or
[song retain]; //or
[reader retain];
該對象仍然意外地釋放分配。同樣,這個問題只發生在我使用NSTimer時。就像在計時器觸發之前對象被釋放一樣。
順便說一句,請認爲沒有語法錯誤。問題是圍繞對象釋放(運行時)。這不是編譯器錯誤。 – tonex 2010-02-05 14:43:48