2

我看到了这个线程,但在 iOS7 中并不完全清楚,因为编程指南说你可以省略@synthesise属性的关键字。

我想要一个@propertyreadonly外部但在readwrite内部的。我可以只使用@property这样的关键字吗?

编辑:在所提供的答案中,什么会被认为更正确,或者至少更惯用。在类扩展中有一个单独的readwrite属性或直接在实现中访问 ivar?

编辑:为了表明我正在使用类扩展,如答案中所建议的那样。

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

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

2 回答 2

8

如果您想这样做,您可以在类扩展中重新声明该属性。

例如,如果您有一个名为 MyClass 的类:

我的类.h

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

我的班级.m

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

现在公共接口的属性是只读的,而私有接口的属性是读写的。而且您不需要 @synthesize 属性,支持 iVar_username默认情况下可用。

于 2013-09-24T11:14:23.513 回答
3

readonly足够的。

使用

@synthesize username = _someVar;

您可以在username访问中写入_someVar。如果没有synthesize,那么

@synthesize username = _username;

是自动生成的。

于 2013-09-24T11:07:30.927 回答