在Objective-C中使用只读属性更新类

时间:2015-02-03 08:04:17

标签: objective-c design-patterns properties

使用只读属性创建和更新类的好模式是什么?这种类的一个例子

@interface ReadOnlyClass : NSObject

@property (nonatomic, assign, readonly) NSUInteger number;

@end

类用户没有必要调用init构造函数(尽管在Objective-C中实际上无法避免这种情况)或其他任何东西。 Apple使用这种模式,例如在CMLogItemCLLocation中。那么,如何以良好的方式更改/更新number的值?

2 个答案:

答案 0 :(得分:0)

我认为最好的模式匹配问题是Builder模式。

EG:你有你的只读属性是结果,然后是一些函数计算。您可以在

中设置各种参数
-(void) setMathExpression:(NSString) aExpression;
-(void) calculate;

然后用户可以设置表达式,调用calculate然后从readonly属性中获取结果。

答案 1 :(得分:0)

如果我理解你是正确的,number是计算属性或 - 有一个更好的术语 - 取决于属性。 number的值取决于可以自行更改的其他属性。正确的吗?

通常你只需为此写一个显式的setter:

-(NSUInteger)number
{
  return /* your calculation */;
}

例如:您有另一个属性playerName,并且您想要返回字符数。 (好吧,不是很退出,但我需要一个例子。)

-(NSUInteger)number
{
  return [self.playerName length];
}

请注意:由于您覆盖了为只读属性声明的所有方法,因此不会合成任何ivar。

如果计算成本很高或者getter的执行频率远远超过可更改属性的设置者(playerName),那么可以优化将类中的属性更改为读写属性每次更改可更改的属性时设置值。

@interface ReadOnlyClass ()
@property (readwrite, …) NSUInteger number;
…
@end

// number is synthesized in this case
-(void)setPlayerName:(NSString*)playerName
{
   _playerName  = playerName;
   self.number = [playerName length];
}