【问题标题】:NSArray initialization in Xcode 5Xcode 5 中的 NSArray 初始化
【发布时间】:2014-07-22 09:08:12
【问题描述】:

我使用的是 Xcode 5,问题出在以下两个 self.<something> 赋值语句 Xcode 中表示 expected expression,以及在 return 语句中。

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    ​ ​ ​ self.questions​ ​=​ ​[NSArray arrayWithObjects:​ @​"​F​r​o​m​ ​w​h​a​t​ ​i​s​ ​c​o​g​n​a​c​ ​m​a​d​e​?​"​, ​@​"​W​h​a​t​ ​i​s​ ​7​+​7​?​"​, @​"​W​h​a​t​ ​i​s​ ​t​h​e​ ​c​a​p​i​t​a​l​ ​o​f​ ​V​e​r​m​o​n​t​?​",nil​]​;

    ​ ​ ​ ​se​l​f​.​a​n​s​w​e​r​s​ ​=​ [NSArray arrayWithObjects:​ ​@​"​G​r​a​p​e​s​"​,@​"​1​4​"​,@​"​M​o​n​t​p​e​l​i​e​r​"​,nil]​; 

   }
​ ​ ​ ​r​e​t​u​r​n​ ​self;
}

【问题讨论】:

  • init 方法内部不要使用 self.questions ,始终使用烘焙变量 _question =
  • @Spynet 这不是真的。
  • @rckoenes 显然,您需要编写避免副作用的代码,一种方法是避免使用 setter 方法,但是即使使用实例变量,您仍然可以通过调用方法引起副作用当对象未完全初始化时在对象上。所以没有关于在init 中使用self 的一揽子规则,只是你需要理解它。然而,这不是这个问题的目的。

标签: ios iphone objective-c ios7


【解决方案1】:

在编写代码的init 方法时,不要像self.<something> 这样访问您的实例变量,您应该使用_<something 的直接访问方式进行操作,因此请更改

self.questions​ ​=​ ​[NSArray arrayWithObjects:​ @​"​F​r​o​m​ ​w​h​a​t​ ​i​s​ ​c​o​g​n​a​c​ ​m​a​d​e​?​"​, ​@​"​W​h​a​t​ ​i​s​ ​7​+​7​?​"​, @​"​W​h​a​t​ ​i​s​ ​t​h​e​ ​c​a​p​i​t​a​l​ ​o​f​ ​V​e​r​m​o​n​t​?​",nil​]​;

​se​l​f​.​a​n​s​w​e​r​s​ ​=​ [NSArray arrayWithObjects:​ ​@​"​G​r​a​p​e​s​"​,@​"​1​4​"​,@​"​M​o​n​t​p​e​l​i​e​r​"​,nil]​; 

_questions​ ​=​ ​[NSArray arrayWithObjects:​ @​"​F​r​o​m​ ​w​h​a​t​ ​i​s​ ​c​o​g​n​a​c​ ​m​a​d​e​?​"​, ​@​"​W​h​a​t​ ​i​s​ ​7​+​7​?​"​, @​"​W​h​a​t​ ​i​s​ ​t​h​e​ ​c​a​p​i​t​a​l​ ​o​f​ ​V​e​r​m​o​n​t​?​",nil​]​;

_​a​n​s​w​e​r​s​ ​=​ [NSArray arrayWithObjects:​ ​@​"​G​r​a​p​e​s​"​,@​"​1​4​"​,@​"​M​o​n​t​p​e​l​i​e​r​"​,nil]​; 

在点表示法 (self.<something>) 上使用直接访问 (_<something>) 的原因是,点表示法会触发其他副作用,例如您可能知道的 KVO 或键值观察。

Initializing a property, dot notation 上有一个可能对您有所帮助的好答案

还有What is the correct way of init iVar variables in presence of ARC

还有Should I refer to self.property in the init method with ARC?

还有Why would you use an ivar?

【讨论】:

  • @Downvoter 请留下拒绝投票的理由,以便我改进我的答案。
  • 我不是反对者,但我认为反对者是因为您的回答不正确。
  • @trojanfoe 请注意我在此之前阅读的其他问题似乎都说同样的话,如果我错了并误解了这些问题的答案,请纠正我。
  • @trojanfoe has answer is not an answer to the question,但答案是合法的,因为您不应该在initdealloc中使用self.
  • 使用属性设置器的问题在于,由于 KVO,它会导致副作用并不明显,这就是为什么在 init/dealloc 中首选实例变量的原因。但是,归根结底,您必须了解在 init 或其他地方调用对象的任何方法的效果,因此没有规则说“您不得在 init 中使用 self”。规则是“了解调用方法(包括 setter)的作用”。
猜你喜欢
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多