【发布时间】:2013-03-07 13:33:44
【问题描述】:
简单地说,我需要一种方法在一个类中拥有一些只对其子类公开的私有方法,而在 Objective-C 中很难(也许不可能)做到这一点。
到目前为止我做了什么:
// MyClass.h
@protocol MyClassProtectedMethodsProtocol
- (void)__protectedMethod;
@end
@interface MyClass : NSObject
- (void)publicMethod;
- (id<MyClassProtectedMethodsProtocol>)protectedInstanceForSubclass:(id)subclass;
@end
然后:
// MyClass.m
#import "MyClass.h"
@interface MyClass() <MyClassProtectedMethodsProtocol>
@end
@implementation MyClass
- (void)publicMethod
{
// something
}
- (id<MyClassProtectedMethodsProtocol>)protectedInstanceForSubclass:(id)subclass
{
if ([subclass isKindOf:MyClass.class] && ![NSStringFromClass(subclass.class) isEqualToString:NSStringFromClass(MyClass.class)])
{
// the subclass instance is a kind of MyClass
// but it has different class name, thus we know it is a subclass of MyClass
return self;
}
return nil;
}
- (void)__protectedMethod
// something protected
{
}
@end
那么MyClass的子类就可以:
id<MyClassProtectedMethodsProtocol> protectedMethodInstance = [self protectedMethodForSubclass:self];
if (protectedMethodInstance != nil)
{
[protectedMethodInstance protectedMethod];
}
这种方式不会破坏 OO(与调用私有方法并忽略编译器警告相比,甚至猜测私有方法名称只知道 .h),但是可用的受保护方法需要一个协议,一旦这个暴露了,在一个我们只向客户端交付接口和静态库的大项目中,客户端实际上可以知道私有方法并尝试调用它们而不管警告。而最大的问题来自子类之外,用户也可以调用这个方法来获取protectedInstance。谁能给点建议?
谢谢
【问题讨论】:
-
单独的标题是执行此操作的规范方法 - 例如查看 UIGestureRecognizer。
标签: ios objective-c oop subclass protected