Accessing Private Properties and Private iVars in Objective C from Another Class
When classes are defined in Objective C, properties are defined as either public or private. Public properties are contained within the .h file and private properties are contained within the .m file. We also have the option of declaring an instance variable which is also private and doesn’t have a property accessor.
The .h file below has an NSArray object called privateArray which is an instance variable, along with a public property called myDictionary, which is an NSDictionary.
In the .m file below there is an NSDictionary private property called myPrivateDictionary.
If we attempt to access the private property from another class, it won’t be available, as shown below.
If we add an @interface definition for MyClass into the ViewController class and include the property for myPrivateDictionary, we will be able to access the private property. As you can see from the screenshot below, Xcode now resolves myPrivateDictionary.
The instance variable privateArray in MyClass is private to that class, although we can use the power of Key-Value Observing (KVO) to access that private instance variable. Bear in mind that if the creator of the class has set accessInstanceVariablesDirectly to FALSE, then this method won’t work.
Let’s run the code to demonstrate it has successfully read the instance variable and set it. As you can see from below it has achieved that goal.
Let’s update the code, so that instance variable is stored in a local variable in the ViewController.m file.
Let’s run the code to see the output, as you can see from below it has failed to change the value of the instance variable, when we accessed the instance variable via KVO, it copied the object rather than assigning a pointer. Bear that in mind and always use setValue when attempting to set a new value for the instance variable when using KVO.
I hope you found this article useful, if you did please like, share or comment.