【问题标题】:Method accessible only to classes in the Static Library只有静态库中的类可以访问的方法
【发布时间】:2015-10-18 21:31:39
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c static-libraries visibility


    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      相关资源
      最近更新 更多