简体   繁体   中英

nonatomic and readonly property in Objective-C

A few times already I wanted to make a property, which is nonatomic and readonly at the same time.

This has the advantage that I can override the getter and check if an instance has already been created or not. And if not I can simply create it.

At the same time I can protect it from being overwritten.


.h

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

.m

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

    return _bar;
}

Whenever I do this, the compiler doesn't create an instance variable for me, so _bar doesn't exist.

Why? How can I create a readonly nonatomic property?

Your property declaration is correct. I believe the problem here is that, because your property was declared as readonly , the compiler didn't automatically synthesize an underlying instance variable. The solution in this case is to synthesize one yourself using...

@synthesize bar = _bar;

You could create a private setter:

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

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

@end

Then when assigning the variable:

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

EDIT

Mark Adam's answer is also correct.

在实现中添加@synthesize bar = _bar。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM