How do I lookup a string constant at runtime in Objective-C?

不羁岁月 提交于 2019-11-26 12:32:09

问题


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;)


回答1:


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);


来源:https://stackoverflow.com/questions/26289301/how-do-i-lookup-a-string-constant-at-runtime-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!