I am a complete newcomer to Object C but I thought I had the idea of memory management at least fundamentally correct. I have this simple method:
-(int)weekIdFromDate:(NSDate *)inDate {
NSCalendar *currentCal = [NSCalendar currentCalendar];
NSDateComponents *component = [currentCal components:NSWeekCalendarUnit fromDate:inDate];
int week = [component week];
//I don't understand why this fails, it seems correct to release these objects now that they
// are no longer needed
[currentCal release];
[component release];
return week;
}
The method exists in my root view controller, but the warning is in the "main"开发者_StackOverflow function. I used a zombie to locate the cause of "BAD_ACCESS...". All works fine with no issues if I comment these to releases out.
You are releasing objects that you don't own.
The methods you use to get currentCal
and component
return autoreleased
objects, which are not your responsibility to release
.
You only call release on objects that you get with new
alloc
or copy
, or objects that you send a retain
message. (Remember the mnemonic NARC).
All explained in the Memory Management Guide
You can only release objects which you own, either by allocating them yourself [[NSString alloc] init]
or retaining objects which already exist [thisVar retain]
. Releasing them just tells the program that you no longer need them. If you allocated them yourself and nothing else has any ownership they will be released from memory, but if something else still has ownership and has not called the release method they will not be released until that object calls the release.
However for your program, you are relying on autorelease. When you create your objects, you do not alloc or retain them, therefore they will be lost when their NSAutoreleasePool is drained (at the end of the method unless you are in another thread), and you don't have to worry about them any more.
Basically since you didn't alloc or retain them, you don't have to release them.
Hope this helps.
精彩评论