2011-06-14 119 views
0

什么是这两种方法之间的主要区别:Objective-C的对象创建方法的差异

+ (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; 
} 
+3

第一种方法不是初始化:它是[便利构造函数](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocAllocInit.html)。第二种方法是尝试成为一个初始化程序,但由于它是一个试图表现为实例方法的类方法,因此失败了。作为一个方面说明,第二种方法不遵循Cocoa的命名初始化程序的规则,如'init ...' – 2011-06-14 10:22:32

+0

@Bavarious - +1为您的评论。我已经修复了这个问题中的拼写错误,因为我怀疑@Peter希望第二种方法实际上是一个正确命名的初始化方法。 (方法体当然看起来像他想的那样。) – 2011-06-14 11:02:00

+0

@sherm Pendley - 回滚您的编辑。你已经完全改变了这个问题 - 你认为OP确实犯了很多错别字 - 使它成为一个不同的问题。 – Abizern 2011-06-14 11:55:00

回答

1

第一种方法是创建一个对象调用者不拥有,不得释放的一类方法。第二个(除了原始问题中的拼写错误)是一个初始化程序,并且由于调用方必须与+alloc结合调用它,它会返回调用方拥有且必须释放的对象。

有关完整的说明,包括描述哪些方法名称暗示所有权和哪些不显示,请查看Apple的Memory Management Programming Guide