为什么有些对象在objective-c中使用前不需要初始化?例如,为什么这是NSDate *today = [NSDate date];
合法的?
4 回答
它们在date
方法中被初始化。这是在 Objective-C 中创建自动释放对象的常用方法。这种形式的分配器称为便利分配器。
要了解更多信息,请阅读 Apple 的 Cocoa 核心能力文档中关于对象创建的“工厂方法”段落:http: //developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCreation。 html
要为您自己的类创建便利分配器,请实现一个以您的类命名的类方法(不带前缀)。例如:
@implementation MYThing
...
+ (id)thing
{
return [[[MYThing alloc] init] autorelease];
}
...
@end
today
在静态日期调用中初始化(并自动释放)。
Two parts.
First, as others have mentioned, a method can initialise and then autorelease an object before returning it. That's part of what's happening here.
The other part is how it's defined. Note how most Objective C definitions begin with a -
? The one you mention does not. The signature looks like this:
+ (NSDate*) date;
That is, it's a class method and applies to the class as a whole rather than to an instance of that class.