开发者

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;
}


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜