Reputation: 15827
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 ?
Upvotes: 5
Views: 18612
Reputation: 8027
#import <objc/runtime.h>
TheClassPrivateVars *_data;
object_getInstanceVariable(self, "_theClassPriv", (void**)&_data);
Couldn't you just do this?
Upvotes: 5
Reputation: 52538
Would probably be a good idea if it is an Apple framework to tell us what framework and what property you are talking about, for some educated guesses exactly how foolish or not it is to access that private property. After all, private properties can be gone tomorrow. And you won't be able to get your app on the App Store easily.
Upvotes: -1
Reputation: 960
TheClassPrivateVars* private = [instanceOfTheClass valueForKey:@"_theClassPriv"];
EDIT: or using key path:
theValue = [[instanceOfTheClass valueForKeyPath:"_theClassPriv.thePrivateProperty"] integerValue];
Upvotes: 14