【问题标题】:Is this the correct syntax, myField_ = [newValue retain]?这是正确的语法吗,myField_ = [newValue retain]?
【发布时间】:2012-08-15 06:05:00
【问题描述】:

我正在尝试学习 Objective C。我遇到了编译器在后台为@property(nonatomic, retain) NSString* myField 生成的以下代码

-(NSString*) myField
{
   return myField_; //assuming myField_ is the name of the field.
}

-(void) setMyField:(NSString*) newValue
{
  if(newValue != myField_)
  {
     [myField_ release];
     myField_ = [newValue retain];
  }
}

现在我的问题是;为什么要在 newValue 上调用保留?相反,应该使用以下语法:

myField_ = newValue;
[myField_ retain];

请告知为什么不使用上述语法,因为根据我的理解,我们希望保留myField_ 指向的对象?

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    它们是相同的(两者都是正确的)。您不复制对象 - 保留返回相同的指针被保留,所以写起来更短更简洁

    ivar = [newObj retain];
    

    而不是单独分配和保留对象。

    【讨论】:

      【解决方案2】:

      两种语法都是正确的。在第一种情况下,我们还保留myField 指向的对象,因为我们将[newValue retain] 分配给它。

      【讨论】:

      • 感谢安德烈的回复!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多