Paolo Paolo - 3 months ago 9
Objective-C Question

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 ?

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

EDIT: or using key path:

theValue = [[instanceOfTheClass valueForKeyPath:"_theClassPriv.thePrivateProperty"] integerValue];