【问题标题】:Automatic Reference Counting in Cocoa-touch - inline best practiceCocoa-touch 中的自动引用计数 - 内联最佳实践
【发布时间】:2011-10-17 13:42:07
【问题描述】:

在 ARC 用于 ios 开发之前,我一直在 viewDidLoad 中使用类似的东西来设置我的导航项:

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneClicked:)] autorelease];

如何在为我的视图控制器启用 ARC 的同时正确实现这一点,同时保持 1 行交易?

我知道在前面加上 __autoreleasing、__strong 等,但我不知道如何在不将其分成 2 行的情况下创建此 rightBarButtonItem

__autoreleasing UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneClicked:)];
self.navigationItem.rightBarButtonItem = rightBarItem;

【问题讨论】:

  • __autoreleasing 不应以这种方式使用。使用__autoreleasing 的地方是在NSError ** 中经常看到的输出参数,即- (NSString *)doSomethingWithError:(NSError **)error 变为- (NSString *)doSomethingWithError:(NSError *__autoreleasing *)error

标签: ios cocoa-touch automatic-ref-counting


【解决方案1】:

在这种情况下,您不需要使用 __autoreleasing 限定符。 rightBarButtonItem 对赋值对象有强引用,然后释放 rightBarButtonItem 时(释放 UINavigationBar 时)会自动释放赋值对象。

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneClicked:)];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多