使用Objective C / Cocoa从NSDate对象中删除时间组件 [英] Removing time components from an NSDate object using Objective C/Cocoa

查看:69
本文介绍了使用Objective C / Cocoa从NSDate对象中删除时间组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Objective C编写一个简单函数,它接受一个NSDate对象并返回一个NSDate对象,该对象包含相同的日期值,但已从日期中删除了任何时间组件。

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.

例如,如果我要传递值为2010-10-12 09:29:34的NSDate,则该函数将返回2010-10-12 00:00:00。

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.

我正在使用的功能似乎正常工作。但是,当我测试我正在使用Instruments开发的iPhone应用程序时,它报告我正在使用的功能中存在内存泄漏。看看我的功能如下。哪里有内存泄漏?有没有更好的方法来实现我想要的功能?

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?

提前致谢!!

-(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];
}


推荐答案

试试这个:

-(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];
}

这篇关于使用Objective C / Cocoa从NSDate对象中删除时间组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆