Peter Warbo
Peter Warbo

Reputation: 11700

Objective-C object creation methods differences

What would be the main differences between these two methods:

+ (id)videoGameWithTitle:(NSString *)newTitle publisher:(NSString *)newPublisher year:(int)newYear {
    VideoGame *game = [[[VideoGame alloc] init] autorelease];
    game.title = newTitle;
    game.publisher = newPublisher;
    game.year = newYear;

    return game;
}

- (id)initVideoGameWithTitle:(NSString *)newTitle publisher:(NSString *)newPublisher year:(int)newYear {

    self = [super init];

    if(self) {
        self.title = newTitle;
        self.publisher = newPublisher;
        self.year = newYear;
    }
    return self;
}

Upvotes: 0

Views: 224

Answers (1)

Sherm Pendley
Sherm Pendley

Reputation: 13612

The first method is a class method that creates an object that the caller does not own and must not release. The second (aside from the typo in your original question) is an initializer, and since the caller has to call it in combination with +alloc, it returns an object that the caller owns and must release.

For a full explanation, including a description of which method names imply ownership and which do not, have a look at Apple's Memory Management Programming Guide.

Upvotes: 1

Related Questions