Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to write a simple function using Objective C that accepts an NSDate object and returns an NSDate object that contains the same date value but has removed any time components from the date.

For example if I were to pass an NSDate with a value of '2010-10-12 09:29:34' the function would return 2010-10-12 00:00:00.

The I'm using function seems to work properly. However, when I test the iPhone app I'm developing with Instruments it reports there is a memory leak in the function I'm using. Take a look at my function below. Where is there a memory leak? Is there a better way to achieve the functionality I desire?

Thanks in advance!!

-(NSDate *)dateWithOutTime:(NSDate *)datDate
{
    if (datDate == nil)
    {
        datDate = [NSDate date];
    }

    unsigned int      intFlags   = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar       *calendar   = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];

     components = [calendar components:intFlags fromDate:datDate];

     return [calendar dateFromComponents:components];
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

-(NSDate *)dateWithOutTime:(NSDate *)datDate {
    if( datDate == nil ) {
        datDate = [NSDate date];
    }
    NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...