Leem.fin Leem.fin - 1 year ago 63
iOS Question

access private variable without creating a property

Say, I have defined a private variable

class & this class is a singleton:

@implementation MyService {
BOOL isStarted;

My question:

Without creating property & accessors, is there a way to access this private variable from another class after I get a instance of this class
[MyService sharedInstance]
. If there is a way, could you please show me how? Thanks in advance.

(Please don't talk about "it is not recommended to do so" etc. I understand that. I am just curious about the possibility of accessing private field in objective-c in general. )

Answer Source

Hi again=) There is a way - you can get your all class variables on the runtime and there search needed one. Still that is hard way and not recommended. Why do you not want to use properties?

  - (void*)getValueWithName:(const char*)varName forClass:(NSString*)className {
        unsigned int varCount;

        Class theClass = NSClassFromString(className);
        Ivar *vars = class_copyIvarList(theClass, &varCount);

        for (int i = 0; i < varCount; i++) {
            Ivar var = vars[i];

            const char* name = ivar_getName(var);
            if (strcmp(name, varName) == 0) {
                ptrdiff_t offset = ivar_getOffset(var);
                unsigned char* bytes = (unsigned char *)(__bridge void*)self;
                return (bytes+offset);


        return NULL;

And casting value:

NSInteger t = *(NSInteger*)[self getValueWithName:"p" forClass:@"ViewController"];
BOOL checkBool = *(BOOL*)[self getValueWithName:"boolean" forClass:@"ViewController"];
NSString *checkString = *((__unsafe_unretained NSString **)([self getValueWithName:"string" forClass:@"ViewController"]));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download