问题描述
为什么一些对象在使用objective-c之前不需要初始化?
例如为什么这个 NSDate * today = [NSDate date];
legal?
Why do some objects not need to be initialized before use in objective-c?For example why is this NSDate *today = [NSDate date];
legal?
推荐答案
它们在 date
方法中初始化。这是在Objective-C中创建自动释放对象的常用方法。
They are initialized within the date
method. This is a common way to create autoreleased objects in Objective-C. Allocators of that form are called convenience allocators.
要了解更多信息,请阅读Apple的Cocoa Core Competencies文档中关于对象创建的工厂方法段落:
To learn more about that, read the "Factory Methods" paragraph in Apple's Cocoa Core Competencies document about Object Creation: http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCreation.html
要为您自己的类创建方便分配器,请实现一个类方法,命名为你的类(无前缀)。例如:
To create convenience allocator for you own classes, implement a class method, named after your class (without prefix). e.g.:
@implementation MYThing
...
+ (id)thing
{
return [[[MYThing alloc] init] autorelease];
}
...
@end
这篇关于为什么一些对象在使用objective-c之前不需要初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!