Reputation: 6862
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.
@property (strong, readonly, nonatomic) Foo *bar;
- (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?
Upvotes: 3
Views: 2643
Reputation: 22006
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.
Upvotes: 2
Reputation: 30846
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;
Upvotes: 6