NSCalendar dateFromComponents: vs NSDateComponents 日期 [英] NSCalendar dateFromComponents: vs NSDateComponents date
问题描述
假设我有以下初始化 NSDateComponents 的代码:
Say I have the following code which initializes an NSDateComponents:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:1987];
[components setMonth:3];
[components setDay:17];
[components setHour:14];
[components setMinute:20];
[components setSecond:0];
现在我想将组件转换为 NSDate.好像有两种方法:
And now I want to convert the components to an NSDate. It seems like there are two ways:
方法一:
NSDate *date = [calendar dateFromComponents:components];
方法二:
NSDate *date = [components date];
这两种方法有区别吗?如果是,应该使用哪一个?为什么?
Is there a difference between these two methods? If so, which one should be used and why?
推荐答案
NSDate *date = [components date];
与
NSDate *date = [[components calendar] dateFromComponents:comps];
如果您没有为日期组件分配日历,它会返回 nil
.您可以通过设置环境变量 NSObjCMessageLoggingEnabled=YES
来验证在项目方案中,并在生成的消息跟踪 (/tmp/msgSends-NNNN
) 中观察到调用的方法完全相同.
and it returns nil
if you don't have assigned a calendar to the date components.
You can verify that by setting the environment variable NSObjCMessageLoggingEnabled=YES
in the projects scheme, and observe in the generated message trace (/tmp/msgSends-NNNN
) that
exactly the same methods are called.
这意味着你可以调用
NSDate *date = [calendar dateFromComponents:components];
或
[components setCalendar:calendar];
NSDate *date = [components date];
并且这两种方法没有区别.
这篇关于NSCalendar dateFromComponents: vs NSDateComponents 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!