2

I am subclassing a pod's class, and in this class there's a private instance variable that I want to expose and use within my class:

@interface MySuperClass () {
    UIScrollView *_scrollView;
}

Usually with exposing a private member or method, I would use a category like someone previously mentioned here, but I am having a problem doing it with a private instance variable. I read here that Associative References might work, but I wasn't able to make it work.

Community
  • 1
  • 1
Aviram
  • 3,017
  • 4
  • 29
  • 43
  • Did you implement [this](http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/)? – Mundi Feb 08 '15 at 14:57
  • @Mundi I've tried but it didn't work for me, maybe I made a mistake when I implemented it. – Aviram Feb 08 '15 at 15:01
  • I don't think you can. anInstanceOfMySuperClass._scrollView is not possible because the dot notation is for accessing a property. If you really want to do it, perhaps you can write a setter and getter methods to emulate this behavior. – user523234 Feb 08 '15 at 15:30

2 Answers2

6

Try implementing in child class:

- (UIScrollView *)scrollView {
    return [self valueForKey:@"_scrollView"]
}
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
HeTzi
  • 916
  • 9
  • 18
-1

Unfortunately, in Objective-C there is no way to declare private instance variables.

Whatever you want your subclass to be able to see, you'll have to declare in your .h-file. The Associative References that you were talking about work in that exact same way, but they solve a different problem, namely the one of declaring instance variables in a category.

This is due to the design of the language, and I guess it makes sense in the way that .m files are really implementation files, and no other class should actually care about the implementation of another, even with inheritance relationships like subclassing.

The option for you with the private instance variable of that pod's class would be to either put it in a property or indeed implement a category where you add methods to access it.

nburk
  • 22,409
  • 18
  • 87
  • 132
  • I've tried to implement a category consisting with the private instance but it didn't work. – Aviram Feb 09 '15 at 09:33