Pregunta

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?

¿Fue útil?

Solución

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;

Otros consejos

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];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top