使用 Objective C/Cocoa 从 NSDate 对象中删除时间组件
我正在尝试使用 Objective C 编写一个简单的函数,该函数接受 NSDate 对象并返回一个包含相同日期值但已从日期中删除任何时间组件的 NSDate 对象。
例如,如果我要传递值为“2010-10-12 09:29:34”的 NSDate,该函数将返回 2010-10-12 00:00:00。
我正在使用的功能似乎工作正常。然而,当我测试使用 Instruments 开发的 iPhone 应用程序时,它报告我正在使用的函数存在内存泄漏。看看我下面的函数。哪里有内存泄漏?有没有更好的方法来实现我想要的功能?
提前致谢!!
-(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];
}
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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this: