I have this code:
in viewDidLoad:
dateForView = [[NSDate alloc] init]; (dateForView is a NSDate)
and a IBAction:
- (IBAction) addDay{
NSLog(@"dateforview1:%@", dateForView);
dateForView = [dateForView dateByAddingTimeInterval:60*60*24*1];
NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd/MM/yyyy"];
[dataLabel setText:[formatter stringFromDate:dateForView]];
}
When I push a button connected to this IBAction, it’s all ok the first time but it crashes the next time around. This is the result of crash in console:
2011-06-01 11:29:55.238 Prenotazioni[554:707] dateforview1:(
"<UIControlTargetAction: 0x1962d0>"
)
2011-06-01 11:29:55.246 Project[554:707] -[__NSArrayI dateByAddingTimeInterval:]: unrecognized selector sent to instance 0x1ba680
2011-06-01 11:29:55.264 Project[554:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI dateByAddingTimeInterval:]: unrecognized selector sent to instance 0x1ba680'
In
viewDidLoad, you are obtaining anNSDatefor which you hold a reference (since you created it withinit). The first time you runaddDay, you replace this with an autoreleasedNSDatefor which you don’t hold a reference any more. When you leaveaddDay, this reference todateForViewbecomes invalid, and the next time you enteraddDayand try to increment it, your app will crash. The solution is to:dateForViewa property withretainpolicy,self.dateForView = [NSDate date]inviewDidLoad.self.dateForView = [self.dateForView dateByAddingTimeInterval:60*60*24*1]inaddDay.Also, don’t forget to set
self.dateForView = nilin your destructor to avoid leaking memory.