Why do some objects not need to be initialized before use in objective-c?

≯℡__Kan透↙ 提交于 2019-12-10 15:58:22

问题


Why do some objects not need to be initialized before use in objective-c? For example why is this NSDate *today = [NSDate date]; legal?


回答1:


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.:

@implementation MYThing
...

+ (id)thing
{
  return [[[MYThing alloc] init] autorelease];
}

...
@end



回答2:


today is initialized (and autoreleased) inside the static date call.




回答3:


You only need to called an init… method on objects you have allocated by calling alloc. 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 between alloc-init…, thats it.




回答4:


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.



来源:https://stackoverflow.com/questions/5992370/why-do-some-objects-not-need-to-be-initialized-before-use-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!