awsome
awsome

Reputation: 2153

Initializing a readonly property

I was trying to create a property which is readonly. I wanted to initialize with a value from the class creating an instance of this class, e.g.

@property (retain,readonly) NSString *firstName;

And I tried to initialize it like this:

-(id)initWithName:(NSString *)n{ self.firstName = n; }

Once I did this, the compiler reported an error that the readonly property cannot be assigned. So how can i do this ?

Upvotes: 29

Views: 20305

Answers (3)

Daniel Vogelnest
Daniel Vogelnest

Reputation: 959

You can directly access the property with:

_firstName = n;

The setter method that self.firstName = n implies will not be synthesized because you specified readonly in @property (retain,readonly) NSString *firstName;, hence the compiler error.

Upvotes: 7

Rengers
Rengers

Reputation: 15238

Don't use the synthesized setter:

firstName = [n retain]; //Or copy

It is generally advised to bypass the setters in any init and dealloc methods anyway.

Upvotes: 14

Ole Begemann
Ole Begemann

Reputation: 135588

Either assign to the instance variable directly (don't forget to add a retain or copy if you need it) or redeclare the property in a private class extension. Like this:

In your .h file:

@property (readonly, copy) NSString *firstName;

In your .m file:

@interface MyClass ()

// Redeclare property as readwrite
@property (readwrite, copy) NSString *firstName;

@end


@implementation MyClass

@synthesize firstName;
...

Now you can use the synthesized setter in your implementation but the class interface still shows the property as readonly. Note that other classes that import your .h file can still call -[MyClass setFirstName:] but they won't know that it exists and will get a compiler warning.

Upvotes: 45

Related Questions