2
votes

I saw this thread, but am not completely clear in iOS7 given the Programming guide says you can leave out the @synthesise keyword for properties.

I want to have a @property that is readonly externally, but readwrite internally. Can I use just the @property keyword like this?

EDIT: What would be considered more correct, or at least more idiomatic, of the answers provided. To have a separate readwrite property in a Class extension or access the ivar directly in the implementation?

EDIT: To show that I am using a Class Extension, as suggested in answers.

//.h
@interface CACustomerAuthenticator : NSObject
@property (nonatomic, copy, readonly) NSString *username;
@end

//.m
@interface CACustomerAuthenticator ()
@property (nonatomic, copy, readwrite) NSString *username;
@end
2

2 Answers

8
votes

If you want to do this you re-declare the property in a class extension.

For example, if you have a class called MyClass:

MyClass.h

@property (nonatomic, copy, readonly) NSString *username;

MyClass.m

// Create a class extension before the @implementation section
@interface MyClass ()
@property (nonatomic, copy, readwrite) NSString *username;
@end

Now the public interface has the property as readonly, and the private interface has it as readwrite. And you don't need to @synthesize the property, the backing iVar is available as _username by default.

3
votes

readonly is enough.

Using

@synthesize username = _someVar;

You are allowed to write in username accessing _someVar. If there's no synthesize, then

@synthesize username = _username;

is automatically generated.