【问题标题】:objective-c ARC readonly properties and private setter implementationObjective-c ARC 只读属性和私有 setter 实现
【发布时间】:2011-12-19 19:50:09
【问题描述】:

在 ARC 之前,如果我希望某个属性在使用时是只读的,但在类中可写,我可以这样做:

// Public declaration
@interface SomeClass : NSObject
    @property (nonatomic, retain, readonly) NSString *myProperty;
@end

// private interface declaration
@interface SomeClass()
- (void)setMyProperty:(NSString *)newValue;
@end

@implementation SomeClass

- (void)setMyProperty:(NSString *)newValue
{ 
   if (myProperty != newValue) {
      [myProperty release];
      myProperty = [newValue retain];
   }
}
- (void)doSomethingPrivate
{
    [self setMyProperty:@"some value that only this class can set"];
}
@end

对于 ARC,如果我想覆盖 setMyProperty,您不能再使用保留/释放关键字,这样是否足够且正确?

// interface declaration:
@property (nonatomic, strong, readonly) NSString *myProperty;

// Setter override
- (void)setMyProperty:(NSString *)newValue
{ 
   if (myProperty != newValue) {
      myProperty = newValue;
   }
}

【问题讨论】:

    标签: iphone objective-c ios automatic-ref-counting


    【解决方案1】:

    是的,这就足够了,但你甚至不需要那么多。

    你可以的

    - (void)setMyProperty:(NSString *)newValue
    { 
          myProperty = newValue;
    }
    

    编译器会在这里做正确的事情。

    不过,另一件事是你甚至不需要那个。在您的类扩展中,您实际上可以重新指定 @property 声明。

    @interface SomeClass : NSObject
    @property (nonatomic, readonly, strong) NSString *myProperty;
    @end
    
    @interface SomeClass()
    @property (nonatomic, readwrite, strong) NSString *myProperty;
    @end
    

    这样做,您只需要合成,并且您有一个为您合成的私有 setter。

    【讨论】:

    • 感谢 Joshua - 非常有用!从那以后,我一直对最后一件事感到困惑。阅读关于属性here 的 ARC 更改似乎默认情况下,它们是由 @synthesize 用 strong 而不是 assign 实现的。在这种情况下,为了使公共 API 更清洁,最好只指定(非原子,只读),因为公共接口的用户不需要关心或需要知道,在内部,该属性是强大的?希望我在这里有意义。 :)
    • 它只对对象类型很强大,为了让事情更明确,我仍然喜欢使用strongweakassign
    • 确实 strong 仅适用于对象类型,但关于您的公共 API(即头文件)是否需要发布此详细信息的问题仍然存在。这才是我真正要问的问题!
    • 我更喜欢让它更明确
    • 我问了一个类似的问题,我不确定它是否能解决任何问题(我仍然不清楚幕后发生的事情)stackoverflow.com/questions/10694676/…
    【解决方案2】:

    您可以在接口扩展中将您的属性重新声明为readwrite

    @interface SomeClass()
    @property (nonatomic, strong, readwrite) NSString *myProperty;
    @end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 2015-08-14
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多