为什么有些对象在 Objective-C 中使用前不需要初始化?
为什么有些对象在 Objective-C 中使用前不需要初始化? 例如,为什么这个 NSDate *today = [NSDate date];
合法?
Why do some objects not need to be initialized before use in objective-c?
For example why is this NSDate *today = [NSDate date];
legal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两部分。
首先,正如其他人提到的,方法可以初始化对象,然后在返回对象之前自动释放该对象。这是这里发生的事情的一部分。
另一部分是它的定义方式。请注意大多数 Objective C 定义如何以
-
开头?你提到的那个没有。签名看起来像这样:也就是说,它是一个类方法,并且应用于整个类,而不是该类的实例。
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:That is, it's a class method and applies to the class as a whole rather than to an instance of that class.
它们在
date
方法中初始化。这是在 Objective-C 中创建自动释放对象的常见方法。这种形式的分配器称为便利分配器。要了解更多信息,请阅读 Apple 的 Cocoa 核心能力文档中有关对象创建的“工厂方法”段落:http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCreation.html
创建方便的分配器你拥有类,实现一个类方法,以你的类命名(没有前缀)。例如:
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.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.:
today
在静态日期调用中初始化(并自动释放)。today
is initialized (and autoreleased) inside the static date call.您只需对通过调用
alloc
分配的对象调用init...
方法。alloc
仅保留对象所需的空间,创建一个统一的对象。未初始化对象的所有实例变量都设置为零、nil 或该类型的等效值。除了设置为 1 的保留计数之外。
返回对象的所有其他方法都保证返回完全初始化的对象。
alloc
是一个例外。您绝不能对已初始化的对象调用
init...
方法。简单的经验法则是在alloc
-init...
之间使用 1 对 1 的关系,就是这样。You only need to called an
init…
method on objects you have allocated by callingalloc
.alloc
only reserves space needed for the object, creating a an unitialized object.An uninitialized object have all instance variables set to zero, nil, or equivalent for the type. Except for the retain count that is set to 1.
All other methods that return an object are guaranteed to return a fully initialized object.
alloc
is the exception.You must never call an
init…
method on an object that is already initialized. Simple rule on thumb is to use a 1-to-1 relation betweenalloc
-init…
, thats it.