Objective C 编程,将消息传递给 NSDate
Objective C programming, passing message to NSDate
我正在关注 objective-C 的一本书,偶然发现了这个使用 NSLog 语句打印当前日期的示例。我很困惑为什么 NSDate class 在将日期消息传递给它之前没有被实例化(alloc 和 init)。
NSDate * pointerToIt = [NSDate date];
在代码的下方,另一条消息被传递给这个指针..
[pointerToIt timeIntervalSince1970];
我所知道的是,只要指针保存 class 实例的地址,就可以向它发送消息,但是 class 从未实例化,消息仍在传递。有人可以帮我解释一下吗?
date
是一种获取当前日期的特殊方法。它是 NSDate
class 上的静态方法,它执行以下操作:
Creates and returns a new date set to the current date and time.
This method uses the default initializer method for the class, init.
您的代码与文档中的代码几乎相同:
NSDate *today = [NSDate date];
因此 today
对象实际上是隐式正确初始化的。
[NSDate date]
为您完成了 alloc
和 init
。如果您参考documentation,您将阅读。
Creates and returns a new date set to the current date and time.
[NSDate 日期] 是一个 class 工厂方法。在内部,它看起来像这样:
+ (instancetype)date {
return [[self alloc] init];
}
我正在关注 objective-C 的一本书,偶然发现了这个使用 NSLog 语句打印当前日期的示例。我很困惑为什么 NSDate class 在将日期消息传递给它之前没有被实例化(alloc 和 init)。
NSDate * pointerToIt = [NSDate date];
在代码的下方,另一条消息被传递给这个指针..
[pointerToIt timeIntervalSince1970];
我所知道的是,只要指针保存 class 实例的地址,就可以向它发送消息,但是 class 从未实例化,消息仍在传递。有人可以帮我解释一下吗?
date
是一种获取当前日期的特殊方法。它是 NSDate
class 上的静态方法,它执行以下操作:
Creates and returns a new date set to the current date and time.
This method uses the default initializer method for the class, init.
您的代码与文档中的代码几乎相同:
NSDate *today = [NSDate date];
因此 today
对象实际上是隐式正确初始化的。
[NSDate date]
为您完成了 alloc
和 init
。如果您参考documentation,您将阅读。
Creates and returns a new date set to the current date and time.
[NSDate 日期] 是一个 class 工厂方法。在内部,它看起来像这样:
+ (instancetype)date {
return [[self alloc] init];
}