简单地说,我需要一种方法在类中拥有一些仅对其子类公开的私有(private)方法,而在 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];
}
这种方式不会破坏面向对象(与调用私有(private)方法并忽略编译器警告,甚至猜测私有(private)方法名称,因为只有 .h 是已知的),但可用的 protected 方法需要一个协议(protocol),一旦这个暴露出来的是,在一个我们只向客户端提供接口(interface)和静态库的大项目中,客户端实际上可以知道私有(private)方法并尝试调用它们,而不管警告。最大的问题是来自子类之外,用户也可以调用此方法来获取 protectedInstance
。谁能给点建议吗?
谢谢
最佳答案
检查这个:Protected methods in Objective-C
简单地说,没有办法阻止在 Objective-C 中调用方法,因为最终客户端仍然可以在任何对象上调用 performSelector
。
关于ios - objective-c : Need suggestion for my way of having protected method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489964/