gpt4 book ai didi

ios - Objective-C : Need suggestion for my way of having protected method?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:07 25 4
gpt4 key购买 nike

<分区>

简单地说,我需要一种方法让类中的一些私有(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];
}

这种方式不会破坏 OO(相比于调用私有(private)方法并忽略编译器警告,甚至猜测私有(private)方法名称,因为只有 .h 是已知的),但是可用的 protected 方法需要一个协议(protocol),一旦这个暴露了,在我们只向客户端交付接口(interface)和静态库的大项目中,客户端实际上可以知道私有(private)方法并尝试调用它们而不管警告。而最大的问题是来自子类之外,用户也可以调用这个方法来获取protectedInstance。任何人都可以建议吗?

谢谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com