![](/img/trans.png)
[英]No 'assign', 'retain', or 'copy' attribute is specified - 'assign' is assumed
[英]Clarification on assign, retain, copy, strong?
我對Objective-C還是陌生的,並且在嘗試找出設置屬性時使用賦值,保留,復制,強等的適當方法時遇到了一些困難。
例如,我聲明了以下類型-應該如何設置屬性?
@property (nonatomic, ??) NSMutableArray *myArray
@property (nonatomic, ??) NSString *myString
@property (nonatomic, ??) UIColor *myColor
@property (nonatomic, ??) int *myIn
@property (nonatomic, ??) BOOL *myBOOL
謝謝....
重申一下,它確實取決於上下文。 在非ARC情況下:
@property (nonatomic, copy) NSMutableArray *myArray
@property (nonatomic, copy) NSString *myString
@property (nonatomic, retain) UIColor *myColor
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) int myInt
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) BOOL myBOOL
myArray上的副本是為了防止您設置的對象的另一個“所有者”進行修改。 在ARC項目中,情況有所變化:
@property (nonatomic, copy) NSMutableArray *myArray
@property (nonatomic, copy) NSString *myString
@property (nonatomic, strong) UIColor *myColor
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) int myInt
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) BOOL myBOOL
更改主要是針對您所處的myColor。 您不會直接使用引用計數,因此不會使用retain
。 strong
關鍵字是斷言屬性的“所有權”的一種方法,類似於retain
。 還提供了另一個關鍵字weak
,通常用於代替對象類型的assign。 蘋果公司普遍存在的weak
就是代表。 除了內存管理指南外,我建議您仔細閱讀《 過渡到ARC發行說明》 ,因為細微之處要比SO帖子中容易涵蓋的細致得多。
@property (nonatomic, copy) NSMutableArray *myArray
@property (nonatomic, copy) NSString *myString
@property (nonatomic, retain) UIColor *myColor
@property (nonatomic) int myIn
@property (nonatomic) BOOL myBOOL
復制可變對象或具有可變子類的對象(例如NSString
:這將阻止其他所有者對其進行修改。 盡管我不認為蘋果推薦使用可變對象作為屬性
通常保留其他對象,除了代表以外,其他對象被分配以防止所有權循環
分配了int
和BOOL
類的原語,這是@property的默認選項,因此無需指定,盡管如果您認為添加它有助於提高可讀性,也可以添加它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.