简体   繁体   中英

readonly public, readwrite private property

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

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.

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.

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