Search code examples
iosobjective-cmemory-managementnscalendar

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 setSecond: 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

Solution

  • 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.