![](/img/trans.png)
[英]Properties in Objective C (readwrite for self and readonly for others)
[英]Objective-C : (private / public properties) making a property readonly for outside class calls and readwrite for self calls
您是否知道一種方法可以為外部調用創建一個屬性readonly並為內部調用進行readwrite?
我以前讀過很多東西
在.h
@property(nonatomic, readonly) NSDate* theDate;
在他們中
@interface TheClassName()
@property(nonatomic, retain) NSDate* theDate;
@end
但是在編譯.m時,這會引發警告“TheClassName類繼續中的屬性theDate屬性與類TheClassName屬性不匹配”。
無論如何,它似乎工作(可以閱讀,但不能從課外設置,可以從內部做兩個)但我應該錯過somehting以避免警告。 或者,如果你知道更好的方法來做到這一點......
在你的.h:
@property(nonatomic, retain, readonly) NSDate* theDate;
在你的.m:
@interface TheClassName()
@property(nonatomic, retain, readwrite) NSDate* theDate;
@end
如果您轉向ARC,這個問題基本上已經消除。 您將在標頭中聲明一次,而不是兩個屬性聲明。
@property(nonatomic, readonly) NSDate* theDate;
然后在類擴展中,只需聲明一個__strong實例變量。
@interface TheClassName()
{
__strong NSDate* _theDate;
}
@end
並在實現中適當地合成它們
@implementation TheClassName
@synthesize theDate = _theDate;
現在您可以設置實例變量。
_theDate = [NSDate date];
ARC將神奇地將適當的保留/釋放功能內聯到您的代碼中,以將其視為強/保留變量。 這樣做的優點是比舊樣式(保留)屬性更快,ARC在編譯時內聯保留/釋放代碼。
如果屬性由變量支持,則該類的變量是默認的類內部讀寫。 將屬性設置為只讀,您的設計目標將得到滿足。 在類中,請參考變量而不預先self.
。
在.m中,你不應該再次放置@property。 不過,我不確定它會產生什么影響。 你的意思是使用@synthesize嗎?
請注意,無論如何,無論是對外部世界的只讀,都將在類實現中讀/寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.