gpt4 book ai didi

ios - 只能由静态库中的类访问的方法

转载 作者:行者123 更新时间:2023-11-29 01:48:19 24 4
gpt4 key购买 nike

我正在为 iOS 构建一个静态库,我希望库中的所有类都可以访问一些方法,但库外的类不能访问。让我们举个例子:

这是一个名为 A 的类,有两个库外可用的方法:

@interface A : NSObject

-(void)methoAvailableOutside1;
-(void)methoAvailableOutside2;

//This method has to be visible only to classes within the library
-(void)methodInternalToTheLibrary;

@end

名为 B 的类仍然在库内部。它可以调用属于 A 的所有方法(也是应该是“内部”的方法):

#import "A.h"

@interface B : NSObject

@property A* aObject;

@end

这是 B 的实现:

#import "B.h"

@implementation B

-(instancetype)init{
self = [super init];

if(self){
_aObject = [[A alloc]init];
[_aObject methoAvailableOutside1];
[_aObject methoAvailableOutside2];

//here I can call the "internal" method
[_aObject methodInternalToTheLibrary];
}

return self;
}

@end

现在让我们编写一个 EXTERNAL 类(显然是在库外部):

#import "MyCustomLibrary.h"

@interface ExternalClass : NSObject

@property A* aObject;

@end

这是外部类的实现:

#import "ExternalClass.h"

@implementation ExternalClass

- (instancetype)init
{
self = [super init];

if (self) {
_aObject = [[A alloc]init];
[_aObject methoAvailableOutside1];
[_aObject methoAvailableOutside2];

//!!!Here THIS SHOULD BE...
[_aObject methodInternalToTheLibrary];
//...FORBIDDEN!!!
}

return self;
}

@end

我怎样才能做到这一点?提前谢谢你。

最佳答案

我能想到的唯一方法是有一个额外的头文件,在该头文件中定义了额外的方法。匿名类别。

publicHeader.h
@interface A : NSObject
-(void)methoAvailableOutside1;
-(void)methoAvailableOutside2;
@end

然后是仅在您的库代码中使用的母 .h 文件。

privateHeader.h
@interface A()
//This method has to be visible only to classes within the library
-(void)methodInternalToTheLibrary;
@end

这行得通吗?它不能保证其他代码不能调用该方法,但意图很明确。

关于ios - 只能由静态库中的类访问的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674410/

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