我目前正在使用 iOS 5 SDK 尝试开发我的应用程序。 我正在尝试使 NSString 成为属性,然后在 .m 文件中合成它(我之前已经这样做了,没有任何问题)。现在,我遇到了这个问题:“语义问题:属性的合成 getter 遵循 Cocoa 命名约定以返回‘拥有’对象。”
这是我的代码: .h
@interface ViewController : UIViewController {
NSString *newTitle;
}
@property (strong, nonatomic) NSString *newTitle;
.m
@synthesize newTitle;
有人知道我该如何解决这个问题吗? 谢谢!!
最佳答案
我的猜测是您使用的编译器版本如下 the memory management rules对于声明的属性,更具体地说,对于声明的属性的访问器:
You take ownership of an object if you create it using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”.
一个名为 newTitle
的属性在合成时会产生一个名为 -newTitle
的方法,因此会出现警告/错误。 -newTitle
应该是 newTitle
属性的 getter 方法,但是命名约定规定名称以 new
开头的方法返回一个对象它归调用者所有,而 getter 方法则不然。
您可以通过以下方式解决此问题:
重命名该属性:
@property (strong, nonatomic) NSString *theNewTitle;
保留属性名称并指定不以特殊方法名称前缀之一开头的 getter 名称:
@property (strong, nonatomic, getter=theNewTitle) NSString *newTitle;
同时保留属性名和getter名,并告诉编译器,即使getter名以new
开头,它也属于none
与 new
方法族相对的方法族:
#ifndef __has_attribute
#define __has_attribute(x) 0 // Compatibility with non-clang compilers
#endif
#if __has_attribute(objc_method_family)
#define BV_OBJC_METHOD_FAMILY_NONE __attribute__((objc_method_family(none)))
#else
#define BV_OBJC_METHOD_FAMILY_NONE
#endif
@interface ViewController : UIViewController
@property (strong, nonatomic) NSString *newTitle;
- (NSString *)newTitle BV_OBJC_METHOD_FAMILY_NONE;
@end
请注意,即使此解决方案允许您将 newTitle
保留为属性名称和 getter 名称,但有一个名为 -newTitle
的方法不会返回调用者拥有的对象可能会让其他阅读您的代码的人感到困惑。
作为记录,Apple 已发布 Transitioning to ARC Release Notes ,他们在其中声明:
You cannot give a property a name that begins with
new
orcopy
.
他们已经被告知他们的陈述不太准确:罪魁祸首是 getter 方法名称,而不是属性名称。
2015 年 1 月 17 日编辑:我刚刚注意到 recent commit to Clang这建议上面的选项 3(使用 objc_method_family(none)
),包括一个修复它,用于属性名称与特殊方法系列前缀之一匹配的一般情况。 Xcode 最终可能会包含此更改。
关于objective-c - 语义问题 : Property's synthesized getter follows Cocoa naming convention for returning 'owned' objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327448/