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

时间:2015-07-28 11:02:53

标签: ios objective-c static-libraries visibility

我正在为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

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

1 个答案:

答案 0 :(得分:1)

我能想到的唯一方法是使用该标头中定义的附加方法获得额外的头文件。匿名类别。

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

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

相关问题