lampShade
lampShade

Reputation: 4391

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

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

Upvotes: 4

Views: 258

Answers (4)

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

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

Upvotes: 4

Stephen Darlington
Stephen Darlington

Reputation: 52565

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.

Upvotes: 0

PeyloW
PeyloW

Reputation: 36752

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.

Upvotes: 0

Kai Huppmann
Kai Huppmann

Reputation: 10775

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

Upvotes: 1

Related Questions