【问题标题】:Objective-C: ARC forbids explicit message send of 'retain'Objective-C:ARC禁止“保留”的显式消息发送
【发布时间】:2013-01-05 23:40:27
【问题描述】:
我是 Objective-C 的新手,我尝试将使用旧版本 Objective-C 编写的旧 Objective-C 项目移植到新项目中,但出现以下编译器错误:
ARC forbids explicit message send of 'retain'
in
color = [aColor retain];
or
color = [[NSColor blackColor] retain];
我正在阅读有关 clang 现在使用的新自动引用计数的信息。
我也尝试过使用 Xcode 的重构功能,但没有运气......
需要替换旧代码的正确 Objective-C 代码是什么?
【问题讨论】:
标签:
objective-c
automatic-ref-counting
retain
【解决方案1】:
简单地说:
color = [NSColor blackColor];
ARC 将管理您的对象的生命周期,因此您不再需要 release、retain 或 autorelease。
【解决方案2】:
ARC 的主要优点是编译器会自动清除您在项目中创建的所有对象的引用。所以不需要保留、释放和自动释放。但在某些情况下,我们希望从 ARC 发布我们的特定文件。在 xcode 中从 ARC 发布您的项目。请按照以下步骤操作。
1.Click your project for Build Phases.
2.Click the drop down menu named as "Compile Sources".
3.Double Click the file that you want to free from ARC.
4.Type the following to set the compiler flag.
"-fno-objc-arc"
此标志将从 xcode 中编译器的 ARC 释放该特定文件。
我希望这将对您的所有项目有所帮助。
【解决方案3】:
只需删除保留,所以:
color = [NSColor blackColor]
使用 ARC,您不能使用 retain、release、autorelease,因为它会为您使用。