【问题标题】:Property attribute "retain" doesn't seem to be working?属性属性“保留”似乎不起作用?
【发布时间】:2010-11-16 00:02:48
【问题描述】:

我已经从许多 Apple 代码示例之一中实现了一些代码,但我遇到了一些麻烦,因为其中一个属性的保留属性似乎不起作用。这是属性声明:

@property (nonatomic, retain) EditingViewController *editingViewController;

这是代码:

- (EditingViewController *)editingViewController {
    // Instantiate the editing view controller if necessary.
    if (editingViewController == nil) {
        EditingViewController *aController = [[EditingViewController alloc] init];
        editingViewController = aController;
        [aController release];
    }
    return editingViewController;
}

我了解 (retain) 应该会导致保留计数在分配时增加 1;但是,除非我自己发送 [aController retain],或者 发送 [aController release],否则代码会失败。我在这里错过了什么?

【问题讨论】:

    标签: objective-c iphone memory-management properties retain


    【解决方案1】:

    当您引用editingViewController 时,它相当于self->editingViewController,即对ivar 的访问。

    如果要使用 getter 或 setter,则需要使用 self.editingViewController,或等效的 [self setEditingViewController:aController]

    这就是为什么我更喜欢使用与属性名称不同的 ivar,例如:

    EditingViewController* i_editingViewController;
    
    @property (nonatomic, retain) EditingViewController *editingViewController;
    
    @synthesize editingViewController = i_editingViewController;
    

    然后你可以把你的惰性吸气剂写成:

    - (EditingViewController *)editingViewController {
        // Instantiate the editing view controller if necessary.
        if (i_editingViewController == nil) {
            i_editingViewController = [[EditingViewController alloc] init];
        }
        return i_editingViewController;
    }
    

    - (EditingViewController *)editingViewController {
        // Instantiate the editing view controller if necessary.
        if (i_editingViewController == nil) {
            EditingViewController *aController = [[EditingViewController alloc] init];
            self.editingViewController = aController;
            [aController release];
        }
        return i_editingViewController;
    }
    

    我可能会使用前一种方法(不调用 setter),因为 editingViewController 的值(正如任何观察者所看到的)并没有真正改变,但任何一种方式都应该可以正常工作并且不同的名称(对于 ivar 和 property ) 有助于避免混淆或意外误用。使用该属性也是一种温和的鼓励(因为它避免了有点难看的前缀)。

    请注意,Apple 保留了 _ 前缀,并且不应在 init/dealloc 例程中使用 setter 和 getter。

    【讨论】:

    • 代码示例确实帮助我看到了我的方式的错误。当我对此进行故障排除时,我试图在所有三个实例上使用 self.editingViewController,这当然是为其中两个实例递归调用 tableView:editingViewController。呵呵。
    【解决方案2】:

    您必须写self.editingViewController 才能使用该属性。只是 "editingViewController" 是对 Class 成员变量的直接访问,而 self.editingViewController 等效于 [self setEditingViewController:...] 并将执行适当的保留/释放工作。

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2010-10-08
      • 1970-01-01
      • 2010-12-08
      • 2013-07-31
      • 1970-01-01
      • 2015-10-05
      • 2014-02-24
      • 2021-09-12
      相关资源
      最近更新 更多