Objective c 在不重写父getter/setter的情况下合成ivar声明
我有两个相互继承的基本类: 基类:Objective c 在不重写父getter/setter的情况下合成ivar声明,objective-c,ios,macos,inheritance,getter-setter,Objective C,Ios,Macos,Inheritance,Getter Setter,我有两个相互继承的基本类: 基类: // .h @interface BaseClass : NSObject @property int myProperty; @end // .m @synthesize myProperty = _myProperty; // .h @interface Child : BaseClass @end 子类: // .h @interface BaseClass : NSObject @property int myProperty; @end //
// .h
@interface BaseClass : NSObject
@property int myProperty;
@end
// .m
@synthesize myProperty = _myProperty;
// .h
@interface Child : BaseClass
@end
子类:
// .h
@interface BaseClass : NSObject
@property int myProperty;
@end
// .m
@synthesize myProperty = _myProperty;
// .h
@interface Child : BaseClass
@end
在ChildClass.m
中,我想使用\u myProperty
ivar访问BaseClass
myProperty
的getter/setter:
// ChildClass.m
_myProperty = 1;
当然,父级的@synthesis
在ChildClass
中不可见,因此我不能只使用\u myProperty
如果我将@synthesis myProperty=\u myProperty
放在ChildClass.m
中,则会覆盖父级的getter/setter,这不是我想要的
有没有一种方法可以在不重写父类方法的情况下生成别名?您将无法使用ivar名称
\u myProperty
,但您可以(并且应该)使用超类的访问器方法:
prop = self.myProperty;
[self setMyProperty:newVal]; //or self.myProperty = newVal if you prefer
手动声明它。然后,您可以完全控制IVAR的范围访问
@protected
提供子类访问,并且@package
使它对实现映像中的所有内容都可见(在无法实现自己的共享框架映像的iOS中并不真正有用)
有关详细信息:
有一种方法,但您必须使支持ivar可见:
@interface MyTest : NSObject
{
@public
int _foo;
}
@property int foo;
@end
@interface MyTestSuper : MyTest
@end
那么要做到这一点:
MyTestSuper *x = [MyTestSuper new];
x->_foo = 5;
附言:如果你只是用“foo”作为支持ivar,这就行了。谢谢,但这正是我不想做的。如果您认为我无法通过
\u myProperty
(使用一种别名)访问myProperty
,那么这个问题可能没有答案。这是可悲的。你可以公开一个变量,但实际上从未公开过,而且通常被认为是糟糕的设计。出于好奇,你为什么不能使用访问器?这就是他们在那里的目的。