vendredi 26 mai 2017

Access to iOS SDK constant via name (reflection)

Inside of iOS SDK, lots of constants defined by Apple can be found looking something like this:

extern const CFStringRef kSomeReallyNiceConstant
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_8_0);

If I check for presence of this constant standard way:

if (NULL == &kSomeReallyNiceConstant)

I am pretty much referencing it and in order for my code to compile properly, I need at least iOS SDK 8.0 or higher in this case.

When it comes to objects and methods, reflection approach works nicely with usage of NSClassFromString, respondsToSelector and performSelector.

Is there a chance to use some kind of reflection (access to string constant by name) in attempt to get it's value if it exists (or none if it doesn't)?

I know that I can use macros to check for iOS version and execute different code paths based on that information, but I don't want to use that approach.

I managed to do this with pointer:

#include <dlfcn.h>

// ...

int *pointer = dlsym(RTLD_SELF, "kSomeReallyNiceConstant");

if (pointer) {
    NSLog(@"Thing exists!");
} else {
    NSLog(@"Nope, doesn't exist!");
}

but I am not sure if this is something that would cause app rejection. Do you maybe know?

Regardless of this pointer approach, I'm curious to hear if there's any other way to achieve this?





Aucun commentaire:

Enregistrer un commentaire