views:

133

answers:

1

I have:

NSDate *d = [[NSDate alloc] init];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *dc = [calendar components:unitFlags fromDate:d];
// doing something with dc.day, dc.month, dc.year
[dc release];
[d release];

I've tried removing the "doing something.. part", just did a get and release, and it still crashes. If I just comment out the [dc release] part, it all works fine.

I'm new to Obj-C. Any idea why this crashes? Am I doing something wrong?

+3  A: 

You shouldn't be releasing dc. It does not come from an alloc, new, or copy.

Brush up on the Cocoa Memory Management Rules

nall
You're right, it says it on the page.But I get a pointer to that new object (created by the calendar), and the calendar no longer does anything with it (it doesn't know when I'm done with it). So the calendar doesn't know when to release it, when does it get released?
Prody
The instance returned to you by the calendar will be autoreleased. It will be released at the next autorelease pool release/drain time (often the end of the event loop). You should retain it if you want to refer to it outside of the scope of this method.
nall
I guess you're right too, but I read that the autorelease thing is not available on the iPhone for performance reasons. I'll have to read about that. Thanks a lot, this helped me :)
Prody
You may be thinking about garbage collection, which is not currently available on the phone. Note that garbage collection and the autorelease pool are two different concepts.
nall
Knowing how to handle memory management is FUNDAMENTAL to Cocoa. Please do not try to go on something you heard about someplace. READ THE PROPER GUIDE.
Mike Abdullah