Clarify Objective-C categories in separate file

穿精又带淫゛_ 提交于 2019-12-23 03:38:35

问题


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?


回答1:


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:

Building Objective-C static libraries with categories

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)
// ...



回答2:


You need to set some flags for the linker... please refer to What does the -all_load linker flag do? for details.



来源:https://stackoverflow.com/questions/6029921/clarify-objective-c-categories-in-separate-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!