Search code examples
objective-cxcodelinkerobjective-c-category

Can Xcode tell me if I forget to include a category implementation in my target?


I have a category that I import in a .m thusly:

#import "UIView+Additions.h"

If I forget to add UIView+Additions.m to my target, I won't know until runtime when the runtime can't find my selector. Is there a way to find out at compile time (or probably link time) that I forgot to include a category's implemtation?


Solution

  • This macro works!

    #ifndef HJBObjCCategory_h
    #define HJBObjCCategory_h
    
    #define HJBObjCCategoryInterface( c , n ) \
    \
    extern int c##n##Canary; \
    \
    __attribute__((constructor)) static void c##n##CanaryCage() { \
        c##n##Canary = 0; \
    } \
    \
    @interface c (n)
    
    #define HJBObjCCategoryImplementation( c , n ) \
    \
    int c##n##Canary = 0; \
    \
    @implementation c ( n )
    
    #endif
    

    Use it like this:

    UIView+Additions.h

    HJBObjCCategoryInterface(UIView, Additions)
    
    - (void)hjb_foo;
    
    @end
    

    UIView+Additions.m

    HJBObjCCategoryImplementation(UIView, Additions)
    
    - (void)hjb_foo {
      NSLog(@"foo!");
    }
    
    @end