【问题标题】:Access private variables of a class in other project访问其他项目中某个类的私有变量
【发布时间】:2019-05-13 14:21:51
【问题描述】:

我有一个庞大的 Objective-C 项目,我想在一个 WorkSpace 中拆分成多个项目。最初我是这样做的,并且代码编译得很好,但我也决定将一个大类的一个类别移到另一个项目中,现在链接器不理解这种情况:

Undefined symbols for architecture x86_64:
  "_OBJC_IVAR_$_MyClass.data", referenced from:
      -[MyClass(Viz) someTask] in MyClass+Viz.o

d: symbol(s) not found for architecture x86_64  
clang: error: linker command failed with exit code 1 (use -v to see invocation)

简而言之,我的工作空间如下所示:

- MyLib project:
    MyClass.h
    MyClass.m
    MyClass+Inner.h
    MyClass+Inner.m

- MyApp project:
    MyClass+Viz.h
    MyClass+Viz.m

MyLib 被编译成MyLib.framework 在MyApp 中使用。正如我所说,在将MyClass+Viz 移动到 MyApp 项目之前,所有复杂的逻辑都可以正常工作,因此项目链接可能没有问题。此外,我在 Build Phases 设置部分中检查了所有文件是否正确标记。

这是MyClass.h 文件:

@interface MyClass : NSObject
- (instancetype)init;
- (void)public_methods;
@end

这是MyClass+Inner.h 文件:

#import "MyClass.h"

@interface MyClass ()
{
    // Variables placed here
    // so that only class methods can access them
    SomeStruct* data;
    // other fields ...
}
@end

@interface MyClass (Inner)
- (void)private_methods;
@end

还有MyClass+Viz.m 文件:

#import "MyClass+Viz.h"
#import "MyClass+Inner.h"

@implementation MyClass (Viz)
 - (int)someTask {
    return data->length;
    // this or any other stuff with
    // class variables from MyClass+Inner.h
    // leads to "Undefined symbols" by linker
}
@end

我怎样才能让它工作,让链接器看到来自其他项目的类的私有变量?

【问题讨论】:

    标签: objective-c xcode oop project


    【解决方案1】:

    首先,您通常应该使用@property 而不是实例变量。

    其次,你会使用多个头文件和类扩展来做这样的事情。

    通常情况下,

    MyClass.h MyClass_Internal.h 我的班级.m MyClass_Internal.m(不常用)

    MyClass.m 将导入两个标题。 MyClass.h 将定义公共接口,而 MyClass_Internal.h 将有一个类扩展来提供私有接口:

    @interface MyClass()
    @property(...) Thing *internalThing;
    @end
    

    【讨论】:

    • 1.是的,我刚刚检查了属性,它们运行良好。但是你能告诉我,如果变量在其他项目中实现,为什么不能从一个类别访问变量? 2.我想我已经使用了多个头文件和类扩展?虽然它被称为类别。
    • @AivanF。类别和类扩展是两个不同的东西。它们有不同的用途。
    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2015-09-25
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多