【问题标题】:ObjectiveC: Need suggestion for my way of having protected method? [duplicate]目标 C:需要对我使用受保护方法的方式提出建议吗? [复制]
【发布时间】: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


【解决方案1】:

检查这个:Protected methods in Objective-C

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

【讨论】:

  • 您应该投票关闭问题作为重复项,而不是发布指向重复项的链接。
  • @rmaddy 我并没有真正认为这是重复的,因为 OP 尝试了一种他想要 cmets 的特定方法。但我明白你的意思。
【解决方案2】:

处理这种情况的标准方法是将内部方法包含在单独的标头中,例如MySuperClass_Internal.h。使用类扩展:@interface MySuperClass (Internal)。请勿在 /usr/local/include 或框架中安装 MySuperClass_Internal.h,否则您将库交付给您的客户。

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 2013-03-14
    • 2010-10-30
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多