下面的代碼崩潰了,但是注釋沒有崩潰:
@property (retain) NSDate *lastCurrentDate;
...
@synthesize lastCurrentDate;
- (void)viewWillAppear:(BOOL)animated {
BOOL crash = [lastCurrentDate isEqualToDate:[NSDate date]]);
}
- (void)viewDidDisappear:(BOOL)animated {
//lastCurrentDate = [[NSDate date] retain];
lastCurrentDate = [NSDate date];
}
為什麼retain屬性在objectiveC中不一定保留?
很簡單 因為 你對lastCurrentDate的付值操作是這樣的 lastCurrentDate = otherDate;
這樣就是直接把otherDate assign給了 lastCurrentDate, 他們2個指向統一個Date 但是retainCount確為1
所以otherDate調用release了 lastCurrentDate就指向了一個dealloc對象 在對lastCurrentDate操作就crash了
既然你是用非ARC 而且@property (retain) NSDate *lastCurrentDate retain 聲明了lastCurrentDate
你因該在類裡面這樣使用lastCurrentDate self.lastCurrentDate = otherDate;
這樣就會去調用 setLastCurrentDate 方法來retain住對象 這樣就不會crash
真確代碼:
@property (retain) NSDate *lastCurrentDate;
...
@synthesize lastCurrentDate;
- (void)viewWillAppear:(BOOL)animated {
BOOL crash = [self.lastCurrentDate isEqualToDate:[NSDate date]]);
}
- (void)viewDidDisappear:(BOOL)animated {
//lastCurrentDate = [[NSDate date] retain];
self.lastCurrentDate = [NSDate date];
}