iosobjective-cxcodeweak-linking

Weak linked class in Xcode


My project has an Objective-C class MockupModel that provides mockup information to an iOS Xcode project to help with creating screen shots for the App store.

The project has two targets. The mockup target includes MockupModel.m.

I want the main target (for the actual App) to not include MockupModel.m so that there is no chance of it accidentally being linked in to the shipping App.

However, when I exclude the MockupModel.m from the project using the file's attribute inspector, reasonably enough, the project fails to link. I get an error complaining that the functions of MockupModel are missing.

Is there some way that I can declare MockupModel as optional so that the linker doesn't worry if it is not implemented? At run time my code will check to see if it's available with NSClassFromString(@"MockupModel"), or with [MockupModel class].


Solution

  • In your non-main target, add a user-defined preprocessor directive. You could call it USE_MOCKUP_MODEL. Remove MockupModel.h and MockupModel.m from your main target's file list and surround any source that references MockupModel (or the imports) with:

    #ifdef USE_MOCKUP_MODEL
    //source
    #endif
    

    Examples:

    #ifdef USE_MOCKUP_MODEL
    #import "MockupModel.h"
    #endif
    
    Model *myModel = nil;
    #ifdef USE_MOCKUP_MODEL
    myModel = [MockupModel new];
    #else
    myModel = [RealModel new];
    #endif