Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: accessing instance variables declared as @private

An external framework I'm using in my application defines theClass whose internal structure is opaque.

Its instance variables are not meant to be accessed directly.

@class TheClassPrivateVars;

@interface TheClass : NSObject
{
    @private
    TheClassPrivateVars *_theClassPriv;
}

@end

The framework public interface is not as complete as it should be and (at my I own risk) I want to read one of the private variables of myClass.

Fortunately the framework is supplied with complete source code so I have access to the definition of TheClassPrivateVars:

@interface TheClassPrivateVars : NSObject
{
    int thePrivateInstanceVar; // I want to read this!

    //
    // other properties here...
    //
}

@end

I've made a header file with the above code and included it just in the source file where the "abusive access" have to happen.

theValue = instanceOfTheClass->_theClassPriv->thePrivateInstanceVar;

Unfortunately _theClassPriv is declared as @private.

Is there any way I can get around it without modifying the original header file ?

like image 958
Paolo Avatar asked Feb 17 '14 13:02

Paolo


2 Answers

TheClassPrivateVars* private = [instanceOfTheClass valueForKey:@"_theClassPriv"];

EDIT: or using key path:

theValue = [[instanceOfTheClass valueForKeyPath:"_theClassPriv.thePrivateProperty"] integerValue];
like image 153
Michał Banasiak Avatar answered Nov 13 '22 22:11

Michał Banasiak


#import <objc/runtime.h>

TheClassPrivateVars *_data;
object_getInstanceVariable(self, "_theClassPriv", (void**)&_data);

Couldn't you just do this?

like image 22
David Mulder Avatar answered Nov 13 '22 21:11

David Mulder