How to find a constant string at runtime in Objective-C?

My company is developing an advertising SDK that mediates other ad networks. At runtime, it checks for other ad networks using NSClassFromStringand sends these class messages if they are present.

This works fine for Objective-C objects, but how can I load a string constant at runtime? In this case, I want to check the SDK version, available only with the string constant ( extern NSString* VungleSDKVersion;)

+4
source share
1 answer

You can use CFBundleGetDataPointerForNameto search for a constant value at runtime

NSString *lookupStringConstant(NSString *constantName) {
    void ** dataPtr = CFBundleGetDataPointerForName(CFBundleGetMainBundle(), (__bridge CFStringRef)constantName);
    return (__bridge NSString *)(dataPtr ? *dataPtr : nil);
}

Usage example:

NSString *version = lookupStringConstant(@"VungleSDKVersion");
NSLog(@"Version = %@",version);
+8

All Articles