簡體   English   中英

Objective-C中的非原子和只讀屬性

[英]nonatomic and readonly property in Objective-C

有幾次已經我想作一個屬性,它是nonatomicreadonly在同一時間。

這樣做的好處是我可以覆蓋getter並檢查是否已經創建了一個實例。 如果沒有,我可以簡單地創建它。

同時我可以保護它不被覆蓋。


。H

@property (strong, readonly, nonatomic) Foo *bar;

.M

- (Foo *)bar {
    if (!_bar) {
        _bar = [[Foo alloc] init];
    }

    return _bar;
}

每當我這樣做時,編譯器不會為我創建實例變量,因此_bar不存在。

為什么? 如何創建readonly nonatomic屬性?

您的財產聲明是正確的。 我相信這里的問題是,因為你的屬性被聲明為readonly ,編譯器不會自動合成底層實例變量。 在這種情況下的解決方案是使用...自己合成一個...

@synthesize bar = _bar;

您可以創建一個私有的setter:

@interface YourClass()  // In the .m file 

@property (strong, readwrite, nonatomic) Foo *bar;

@end

然后在分配變量時:

self.bar = [[Foo alloc] init];

編輯

Mark Adam的回答也是正確的。

在實現中添加@synthesize bar = _bar。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM