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.

3
  • Did you implement this? Commented Feb 8, 2015 at 14:57
  • @Mundi I've tried but it didn't work for me, maybe I made a mistake when I implemented it. Commented Feb 8, 2015 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. Commented Feb 8, 2015 at 15:30

2 Answers 2

6

Try implementing in child class:

- (UIScrollView *)scrollView {
    return [self valueForKey:@"_scrollView"]
}
Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

I've tried to implement a category consisting with the private instance but it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.