开发者

do I need to release the NSCalendar object in this code example?

开发者 https://www.devze.com 2023-02-18 14:35 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消