在单独的文件中澄清Objective-C类别 [英] Clarify Objective-C categories in separate file

查看:150
本文介绍了在单独的文件中澄清Objective-C类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在引擎的类别中添加了一些方法。这个类别在我的单独文件中声明和实现。然后我包括这些文件(但所有引擎文件保持不修改,所以只有原始声明包括在引擎中)。引擎构建在静态库中并与我的应用程序链接。当我调用我的类别的方法时,应用程序崩溃,错误无法识别的选择器发送到实例...。但是如果我用原始引擎类声明类别在文件中所有工作。

I have added some methods to existing class in engine by category. This category is declared and implemented in my separate files. Then I include these files (but all engine files stay not modified, so only original declarations are included in engine). Engine is built into static lib and linked with my app. When I call a method of my category the app crashes with error "unrecognized selector sent to instance...". But if I declare category in file with original engine class all works.

为什么类别的选择器不能识别,如果它是在单独的文件中声明和实现?

Why selector of category is not recognized if it's declared and implemented in separate files? Does order of including files matter?

推荐答案

这是一个链接器错误,其中在自己的编译单元中声明的类别方法未正确链接进入应用程序。请参阅这里的苹果技术说明:

This is a linker bug where category methods declared in their own compilation unit are not correctly linked into an app. See the technical note from apple here:

使用类别构建Objective-C静态库

您必须指定链接器标志 -all_load 在你的应用程序中,或者'hacky'技术将定义一个宏,将定义一个虚拟类和实现,并在每个类别实现中调用该宏:

You must either specify the linker flag -all_load in your application, or a 'hacky' technique would be to define a macro which will define a dummy class and implementation, and call that macro in each category implementation:

#define FIX_CATEGORY_LINKER_BUG(name) \
    @interface FIX_CATEGORY_LINKER_BUG_##name @end \
    @implementation FIX_CATEGORY_LINKER_BUG_##name @end

并在类别实现之前使用它:

And use it as follows above your category implementation:

FIX_CATEGORY_LINKER_BUG(NSStringMyAdditions)

@implementation NSString (MyAdditions)
// ...

这篇关于在单独的文件中澄清Objective-C类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆