Varun Naharia
Varun Naharia

Reputation: 5420

How to access protected variable in Objective-C?

I know protected variable can't be access out side the class but is it possible to access them in Category or in SubClass, I think it's not possible for Subclass but is it the same case for Category ?

What I want to do is some modification to a library form github but I don't want to modify the original source code. I want to achieve this through subclassing or using category but the problem is I want reference to some protected variable.

Protected variable in .m file:-

@interface Someclass() {
    NSMutableDictionary *viewControllers;
      __weak UIViewController *rootViewController;
    UIPageViewController *pageController;
}

@end

Upvotes: 0

Views: 325

Answers (1)

Hermann Klecker
Hermann Klecker

Reputation: 14068

A category cannot access private instance variables nor can a subclass do that.

As you have access to the source code and just don't want to change the original source code you could create another class with exactly the same data structure. (same variable names and types declared exactly in the same way and sequence).

@interface Shadowclass() {
    NSMutableDictionary *viewControllers;
      __weak UIViewController *rootViewController;
    UIPageViewController *pageController;
}

@end

Then add getters and setters to Shadowclass to make the values accessible.

The do:

Someclass *someclass = ... // you get the object from somewhere somehow. 
object_setClass(someClass, [ShadowClass class]); 

How someclass is of the type ShadowClass and you can access the getter and setter. Frankly I am not sure how the current compiler allows for accessing the getters directly of if you are allowed to cast someClass now an ShadowClass type object variable, but you can use performSelector for accessing the getters or setters.

Accessability of getters and setters directly like [shadowClass rootViewController:xxx] may even vary whether you are using ARC or not. (The compiler's behaviour here may even be configurable. This, too, I do not know on detail out of the top of my head.)

However, I am not sure whether I really want to recommend that! You may find less "hacky" alternatives. And do not underestimate the importance of creating exactly the same structure for Shadowclass as for Someclass!

Upvotes: 1

Related Questions