开发者

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

开发者 https://www.devze.com 2023-03-06 04: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?They are initialized within the date method. This

Why do some objects not need to be initialized before use in 开发者_运维技巧objective-c? For example why is this NSDate *today = [NSDate date]; legal?


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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消