ios - objective-c : Need suggestion for my way of having protected method?

标签 ios objective-c oop subclass protected

简单地说,我需要一种方法在类中拥有一些仅对其子类公开的私有(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/

相关文章:

objective-c - NSBundle 的 -load 方法如何向 Objective-C 运行时注册类和其他运行时资源?

ios - 如何以编程方式点击 iOS 键盘上的一个点

Javascript 相当于 PHP 的::(范围解析运算符)

android - 附近网络的 BSSID w/Titanium

ios - 如何在 iOS 8 swift 中更改按钮文本大小

ios - 如何构建 .ipa 并将其从 xcode 安装到 iphone 上?

ios - UISplitViewController 的主视图中未调用 viewWillAppear

c++ - 有什么区别: Creating structure pointer inside a structure of the same type with the keyword struct

oop - 向我解释什么是 setter 和 getter

ios - ScrollView 缩放问题中的 UIView