IluTov
IluTov

Reputation: 6862

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?

Upvotes: 3

Views: 2643

Answers (3)

Ramy Al Zuhouri
Ramy Al Zuhouri

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

Diego Allen
Diego Allen

Reputation: 4653

In the implementation add @synthesize bar = _bar.

Upvotes: 1

Mark Adams
Mark Adams

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

Related Questions