do I need to release the NSCalendar object in this code example?
do I need to release the NSCalendar object in this code example? Or will this impact on the fact that the last line of code is to return newDate which is derived from the "gregorian" variable?
#import "NSDateHelper.h"
@implementation NSDate(NSDateHelper)
-(NSDate *) setHour:(NSInteger)hour andMinute:(NSInteger)minute {
// Get Calendar for Existing Date
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: self];
// Set Hour and Minute
[components setHour: hour];
[components setMinute: minute];
[components setSec开发者_JAVA百科ond: 00];
// Create resultant Date
NSDate *newDate = [gregorian dateFromComponents: components];
// Clean Up
[gregorian release]; // TODO: Do I release this here, or will it affect the return value not being valid?
return newDate;
}
@end
Yes, you release.
your components variable will retain what it needs. Since you take ownership by alloc'ing NSCalendar, you are responsible for releasing it.
ps: it is very strange to have a return value for a method named set. I would recommend refactoring to avoid a lot of confusion later on.
Releasing there is fine, newDate
is returned with an autorelease
so it will stick around until an NSAutoreleasePool
is drained. If newDate
requires a reference to the calendar instance it will handle the retain count internally.
The object that alloc'd it should release it too, unless autorelease is used.
Autorelease is not used in this example, so you must indeed release it.
精彩评论