Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a readonly property with a custom getter have an instance variable synthesized?

I have a situation where I don't want instance variables synthesized for a set of properties (I'm managing them via User Defaults and Keychain).

If I have the following, _loginUsername will for sure be synthesized:

@property (nonatomic, readonly) NSString *loginUsername;

And I know if I had the following, an instance variable would not be synthesized, because the declaration is saying "I'm going to take care of it myself":

@property (nonatomic, getter = loginUsername, setter = setLoginUsername) NSString *loginUsername;

Is the behavior the same for a readonly property with a custom getter?:

@property (nonatomic, readonly, getter = loginUsername) NSString *loginUsername;

Will there be a _loginUsername synthesized for the final property declaration? I'm fairly sure that there won't, but I'm trying to get a better grasp of property attributes so want to make sure I'm not way off.

Bonus points for explaining whether this is known at compile time (no cheating and checking in Xcode!).

I don't have any @synthesize statements in my implementation file.

like image 275
bdalziel Avatar asked Mar 06 '14 05:03

bdalziel


People also ask

How do you set a read-only property?

Conclusion # The error "Cannot assign to 'X' because it is a read-only property" occurs when we try to change the value of a read-only property in a class or an object. To solve the error, remove the readonly modifier or use a type assertion to change the value of the property.

What is read-only property in IOS?

Read-only means that we can access the value of a property but we can't assign any value to it.


1 Answers

Note: The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically. If you still need an instance variable, you’ll need to request that one be synthesized

Programming with Objective-c - Encapsulating data - under You Can Implement Custom Accessor Methods

like image 62
3 revs Avatar answered Dec 22 '22 01:12

3 revs