简体   繁体   中英

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, eg

@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 ?

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.

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.

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.

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