简单地说,我需要一种在类中只有一些私有方法的方法,这些方法只针对它的子类公开,而且在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
。有人可以建议吗?
由于
答案 0 :(得分:1)
处理此方案的标准方法是将内部方法包含在单独的标头中,例如MySuperClass_Internal.h
。使用类扩展名:@interface MySuperClass (Internal)
。不要在/ usr / local / include或框架中安装MySuperClass_Internal.h
,或者您将库提供给客户。
答案 1 :(得分:1)
请检查:Protected methods in Objective-C
简单地说,没有办法阻止在Objective-C中调用方法,因为最终,客户端仍然可以在任何对象上调用performSelector
。