iOS ARC下命名規則

來源:互聯網
上載者:User

當我在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
  • newTitleAcceptable Object Names
    • _newButton
    • mewLabel
    • neueTitle

      #arc #auto-synthesized #xcode-4.6.1





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.