views:

92

answers:

2

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?

A: 

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;

lucius
+2  A: 

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.

Cocoa Memory Management Rules

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.

willcodejavaforfood
Thanks guys! I feel stupid. Should have seen that. copied code and changed it..I am not shure why i get 0 back when removing the releases thou.. I do think i am retaining the NSDate value.. I'l check when i get back home..
Larsaronen
It's a difficult concept :)
willcodejavaforfood
The reason the method returned 0 was that [conversionInfo year] returns a NSInteger. I Changed my double's to NSIntegers and it worked perfect!
Larsaronen