Error when releasing NSdate from [NSDateComponents components: fromDate: toDate: options:]
-
26-09-2020 - |
Question
Okay so i got this clas called event.
It has a property called eventDate wich is a NSDate. I made a method to return how many years it is since the event date:
- (double)yearsSinceEvent {
double years;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = self.eventDate;
NSDate *date2 = [NSDate date];
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSYearCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
years = [conversionInfo year];
[date1 release];
[date2 release];
return years;
}
when configuring my tableview cells i do:
cell.textLabel.text = [[events objectAtIndex:indexPath.row] name];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d year's ago", [events objectAtIndex:indexPath.row] yearsSinceEvent]];
But this throws this error:
*** __NSAutoreleaseFreedObject(): release of previously deallocated object (0x595bda0) ignored
What am i doing wrong here?
If i dont release date1 and date2 i dont get the error, but the method returns 0..
If i do the yearsSinceEvent code in the cell configuration method instead, and dont release date 1 and date 2 it works..
How should i do this?
La solution
You should not release date1 and date2 because they're already autoreleased. Make sure your eventDate ivar is properly declared as a retained property: it should be @property (nonatomic, retain) NSDate *eventDate;
Autres conseils
You should not release date1
and date2
in this case.
date2
is created with a factory method and will be autoreleased.
date1
is something you read from another property WITHOUT retaining it so you should not release that one either or self.eventDate will be released.
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.