Vittal Pai Vittal Pai - 1 year ago 57
Objective-C Question

How to make Objective-C Class optional based on Framework loaded?

I have a class file in a framework 'X', The class file uses methods of framework 'Y'. Is there any way to make class file optional when framework 'Y' is not present during run time, Such that it shouldn't throw any compilation errors in a xcode project during compilation of project with framework 'X' and without framework 'Y.

Answer Source

Yes, don't statically load framework Y's class objects by directly pass messages to them.

Let's say framework Y has the class YYYClass. When you reference YYYClass within framework X, you would normally do the following.

YYYClass *instance = [[YYYClass alloc] init];

The call to [YYYClass alloc] is passing a message to YYYClass. Now the linker requires YYYClass to be available.

However do something a little different.

YYYClass *instance = [[NSClassFromString(@"YYYClass") alloc] init];

Now, framework Y's class object is being dynamically loaded so the linker doesn't require the class to be available.

If framework Y is not in the final binary, then NSClassFromString(@"YYYClass") returns Nil (the class version of nil). [Nil alloc] returns nil and [nil init] returns nil.

The end effect is all instances of framework Y's classes will be nil. You need to expect this behavior and handle it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download