iOS ARC下命名规则

当我在ARC模式下写以下代码的时候,编译器报错 

Semantic Issue: Property's synthesized getter follows Cocoa naming convention for returning 'owned' objects

@interface ViewController : UIViewController {

     NSString *newTitle;

}

@property (strong, nonatomic) NSString *newTitle;

.m

@synthesize newTitle;

这是因为在高版本编译器ARC模式下,这种命名规范是不合理的,可以查看苹果官网的内存管理方面的文档中有说明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”.

前面带有 new 的属性在@synthesize的时候会生成getter和setter方法,如果有new打头的属性的时候,在生成getter就会调用newTitle方法,编译器认为这是生成

新的对象,而不是get原有的属性,所以就提示错误信息。


解决办法:

1。new前加上别的字符例如theNewTitle

@property (strong, nonatomic) NSString *theNewTitle;
2。重写getter方法

@property (strong, nonatomic, getter=theNewTitle) NSString *newTitle;
3。第三种是可以new开头,但是要告诉编译器不是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
4。这种也可以啊

@synthesize newTitle = _newTitle; // Use instance variable _newTitle for storage

苹果已经有文档Transitioning to ARC Release Notes说明了开发者在命名的时候避免以 new 和 copy 开头

Unacceptable Object Names

  • newButton
  • newLabel
  • newTitle

Acceptable Object Names

  • _newButton
  • mewLabel
  • neueTitle

#arc #auto-synthesized #xcode-4.6.1





版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/zsw-1993/p/4879579.html