Search code examples
objective-ccocoacocoa-design-patterns

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?


Solution

  • 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