문제

Why the following code crashes? Commented code doesn't crash.

@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];
}

So, why retain property may not retain on Objective-C?

도움이 되었습니까?

해결책

When you write @synthesize lastCurrentDate - you also create variable named 'lastCurrentState', and when you write lastCurrentDate = [NSDate date]; you directly access this variable. Properties should be accessed via dot: self.lastCurrentDate = ....;

In last xCodes you don't need to write synthesize - it do it automatically, but creates variable named with '_' prefix. It equals to: @synthesize variable = _variable;

다른 팁

Use self.lastCurrentDate = [NSDate date]. Because when you use self.lastCurrentDate, it will assign via setter method. You declare vaiable via retain property, So your setter method will do two operation,assign and retain.

Because you assigned directly to the instance variable, instead of using the property accessor method:

self.lastCurrentDate = [NSDate date];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top