Ios 目标C:我的保护方法需要建议吗?

Ios 目标C:我的保护方法需要建议吗?,ios,objective-c,oop,subclass,protected,Ios,Objective C,Oop,Subclass,Protected,简单地说,我需要一种方法,在一个只为其子类公开的类中拥有一些私有方法,而在Objective-C中很难(也许不可能)做到这一点 到目前为止我所做的: // MyClass.h @protocol MyClassProtectedMethodsProtocol - (void)__protectedMethod; @end @interface MyClass : NSObject - (void)publicMethod; - (id<MyClassProtectedMethodsPr

简单地说,我需要一种方法,在一个只为其子类公开的类中拥有一些私有方法,而在Objective-C中很难(也许不可能)做到这一点

到目前为止我所做的:

// MyClass.h

@protocol MyClassProtectedMethodsProtocol
- (void)__protectedMethod;
@end

@interface MyClass : NSObject
- (void)publicMethod;
- (id<MyClassProtectedMethodsProtocol>)protectedInstanceForSubclass:(id)subclass;
@end
这种方法不会破坏OO(与调用私有方法并忽略编译器警告相比,或者甚至猜测私有方法名称仅为.h是已知的),但可用的受保护方法需要一个协议,一旦暴露出来,在我们只向客户机提供接口和静态库的大型项目中,客户机实际上可以知道私有方法并尝试调用它们,而不考虑警告。而最大的问题来自子类之外,用户也可以调用此方法来获得
protectedstance
。有人能给我建议吗


谢谢

处理此场景的标准方法是在单独的头中包含内部方法,如
MySuperClass\u internal.h
。使用类扩展名:
@interface MySuperClass(Internal)
。不要在/usr/local/include或框架中安装
MySuperClass\u Internal.h


简单地说,没有办法阻止在Objective-C中调用方法,因为最终,客户机仍然可以对任何对象调用
performSelector

而不是发布指向副本的链接,您应该投票将问题作为副本关闭。@rmaddy我并不认为这是副本,由于OP尝试了一种特定的方法,他希望得到评论。但我明白你的意思。分开的标题是实现这一点的标准方法——比如看UIGestureRecognitor。
// 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
id<MyClassProtectedMethodsProtocol> protectedMethodInstance = [self protectedMethodForSubclass:self];
if (protectedMethodInstance != nil)
{
    [protectedMethodInstance protectedMethod];
}