【问题标题】:readonly public, readwrite private property只读公共,读写私有属性
【发布时间】:2013-09-24 11:02:19
【问题描述】:

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

我想要一个@property,外部是readonly,内部是readwrite。我可以像这样只使用@property 关键字吗?

编辑:在所提供的答案中,哪些被认为更正确,或者至少更惯用。要在 Class 扩展中拥有单独的 readwrite 属性或直接在实现中访问 ivar?

编辑:按照答案中的建议,表明我正在使用类扩展。

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

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

【问题讨论】:

    标签: ios objective-c properties encapsulation


    【解决方案1】:

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

    例如,如果您有一个名为 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
    

    现在公共接口的属性为只读,而私有接口的属性为读写。而且你不需要@synthesize 属性,支持iVar 默认为_username

    【讨论】:

    • 这是一个比上面更好的答案,因为除非你以某种方式将它们重新声明为 __weak
    【解决方案2】:

    readonly 就够了。

    使用

    @synthesize username = _someVar;
    

    你可以写username访问_someVar。如果没有synthesize,那么

    @synthesize username = _username;
    

    自动生成。

    【讨论】:

    • 你是说我的类扩展中不需要任何东西,只需要接口中的只读属性?
    • 我是否需要在我的实现中直接访问 _username 而不是通过访问器?
    • 是的,但您必须通过 ivar _username 设置用户名属性
    • 谢谢。您认为哪个更惯用,直接使用 ivar 还是在类扩展中使用单独的读写属性?
    • 我会选择 ivar,但我认为这只是编程风格的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2011-03-24
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多