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