添加没有实例变量的属性?

时间:2012-02-27 03:11:23

标签: objective-c properties

我正在尝试添加属性而不创建实例变量。是否有可能做到这一点?或者你可以用不属于财产的方式做类似的事情吗?

示例:

@interface RandomClass()
@property (nonatomic) int value;
@end

@implementation RandomClass
@synthesize value = _value;
// Here I override the default methods @synthesize
-(int)value
{
      return 8; // Actually I'm returning something more complex, so a "define" won't work
}
-(void)setValue:(int)value
{
   self.someOtherValue = value;
}

在上面的代码中,我没有使用实例变量_value!有没有办法在不创建变量的情况下执行此操作?

1 个答案:

答案 0 :(得分:8)

删除行

@synthesize value = _value;

由于您自己实施了getter / setter,@synthesize无效。


@synthesize提供两份工作。第一项工作是将属性连接到支持ivar,如果它不存在则合成ivar。第二项工作是合成getter / setter。如果您不需要支持ivar,并且如果您自己为getter / setter提供实现,那么您根本不需要@synthesize