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

tom*_*cca 12 properties objective-c

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

例:

@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;
}
Run Code Online (Sandbox Code Playgroud)

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

Lil*_*ard 8

删除该行

@synthesize value = _value;
Run Code Online (Sandbox Code Playgroud)

由于您自己实现了getter/setter,因此@synthesize无济于事.


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

  • @claireware:相反,如果编译器可以看到方法已经实现,那么就不需要`@ dynamic`.见["财产实施指令"](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW9 ):<quote>您可以在`@ implementation`块中使用`@ synthesize`和`@ dynamic`指令来触发特定的编译器操作.请注意,任何给定的`@ property`声明都不需要.</ quote> (5认同)
  • @LightningStryk:当且仅当它合成时,编译器才会创建ivar.如果同时实现这两种方法,则不会发生自动合成.如果省略getter或setter(假设是readwrite属性),就会发生这种情况.如果你有一个`@ synthesize`行,你明确告诉编译器合成ivar,即使你同时实现了getter/setter. (4认同)
  • @claireware:Josh是对的.`@ dynamic`告诉编译器不要担心它是否找不到getter/setter,因为它们将在运行时提供.如果你打算在*compile*时提供getter/setter,那么你不需要`@ dynamic`(事实上,更好的是没有它,因为如果你设法忘记,编译器会对你大喊大叫实现getter或setter). (3认同)
  • @JoshCaswell如果你有`@property propertyName`,即使你提供自己的setter/getters,编译器是否还会创建一个ivar? (3认同)