- (ID)initWithname:(Nsstring *)playername { if ((self = [super init])) { self.name = [playername retain]; self.score = [NSNumber numberWithInt:0]; } return self;}
我在这里使用保留吗?或者我可以像self.name = playername;?
此外,假设我想要另一个初始化器,但保持initWithname:playername为指定的初始化器.如何让第二个初始化程序调用第一个?
对于最后一个问题,我知道我也需要覆盖 – (ID)init方法.但是,我在那里做什么?只是分配测试属性,只是用init初始化了类?
谢谢!
解决方法Am I using retain here properly?
不,你不是.你应该使用
self.name = playername;
正如你的建议,或(根据Apple推荐)
name = [playername copy];
不建议在-init中使用访问器,因为子类可能会覆盖它们.
另请注意,当Nsstring实现NScopying时,您应该使用copy属性,而不是retain属性.
Furthermore,assume I want another initializer,but keep the initWithname:playername the designated initializer. How would I make the second initializer call the first?
使用-init作为示例(因为如果指定的初始化程序不相同,则必须覆盖超类的指定初始化程序)
-(ID) init{ return [self initWithname: @"Some default value"];}总结
以上是内存溢出为你收集整理的iphone – Objective-C中的自定义对象初始化全部内容,希望文章能够帮你解决iphone – Objective-C中的自定义对象初始化所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)