合成ivar声明而不覆盖父getter / setter

时间:2012-08-17 21:29:40

标签: objective-c ios macos inheritance getter-setter

我有两个相互继承的基本类:

BaseClass的:

// .h
@interface BaseClass : NSObject
@property int myProperty;
@end

// .m
@synthesize myProperty = _myProperty;

ChildClass:

// .h
@interface Child : BaseClass
@end

ChildClass.m,我想使用BaseClass ivar访问myProperty _myProperty的getter / setter:

// ChildClass.m
_myProperty = 1;

当然,@synthesize无法看到父母的ChildClass,因此我不能只使用_myProperty

如果我将@synthesize myProperty = _myProperty放在ChildClass.m中,父母的getter / setter会被覆盖,而这不是我想要的。

有没有办法在不重写父方法的情况下创建别名?

3 个答案:

答案 0 :(得分:3)

手动声明。然后,您可以完全控制iVars的范围访问。

@protected提供了子类访问权限,@package使实现图像中的所有内容都可见(在iOS中无法实现您自己的共享框架图像时非常有用)。

更多详情:

http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocDefiningClasses.html

答案 1 :(得分:0)

您将无法使用ivar名称_myProperty,但您可以(并且应该)使用超类的访问者方法:

prop = self.myProperty;
[self setMyProperty:newVal];  //or self.myProperty = newVal if you prefer

答案 2 :(得分:0)

有一种方法,但你必须让支持ivar可见:

@interface MyTest : NSObject
{
@public
    int _foo;
}
@property int foo;

@end
@interface MyTestSuper : MyTest
@end

然后去做:

MyTestSuper *x = [MyTestSuper new];
x->_foo = 5;

PS:如果你只是使用“foo”作为支持ivar,这是有效的。

相关问题