6

My company develops an advertising SDK that mediates other ad networks. At runtime, it checks if the other ad networks are present by using NSClassFromString, and sends those classes messages if they're 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 version of an SDK that is only available through a string constant (extern NSString* VungleSDKVersion;)

MaxGabriel
  • 7,617
  • 4
  • 35
  • 82

1 Answers1

10

You can use CFBundleGetDataPointerForName to lookup a constant's value at runtime

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

Example use:

NSString *version = lookupStringConstant(@"VungleSDKVersion");
NSLog(@"Version = %@",version);
MaxGabriel
  • 7,617
  • 4
  • 35
  • 82
  • This is years after the fact, but I wanted to add this wasn't 100% reliable at the time. It seemed to work fine in most cases, but some apps compiled from 3rd party tools seemed to have it fail. I assume some sort of stripping of the metadata causes that? Not sure. – MaxGabriel Jan 10 '22 at 20:33