1

In my case, UIViewController B is a subclass of UIViewController A. B can surely access all the methods and variables from A, since B is subclassing from A (i.e. A is the parent of B).

However, A needs a variable from B. Is there possible to do that ?

Thanks.

user403015
  • 7,209
  • 19
  • 66
  • 100
  • Are you talking about accessing actual variable values at runtime? If so there are a few options, e.g. notifications, saving data to nsuserdefaults, etc. – ader Jan 27 '12 at 09:54
  • I want A (parent) can access the instance variables which set by B (child) in runtime. How to design and code that? – user403015 Jan 27 '12 at 09:57
  • @Ankit Srivastava, would you mind explain it more? – user403015 Jan 27 '12 at 09:59
  • http://stackoverflow.com/a/322627/919545 – Ankit Srivastava Jan 27 '12 at 10:04
  • The superclass should not know anything about the subclass. Can you please detail the scenario you're dealing with? In particular why the superclass would need to access the subclass' variable? – John Mead Jan 27 '12 at 10:01

3 Answers3

0

Add that variable as a default in subclass A. Then it's also available in subclass B?

If that's something you don't want, then I suppose there is something wrong with your design?

Glenn
  • 1,085
  • 1
  • 9
  • 13
0

If the instance variable declared in the subclass has a getter method, any method in the superclass could always ask an object of its class if it respondsToSelector: for that getter method, and if so, call it to get the value of the instance variable.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
0

Actually, if you need this type of relations - your design is wrong. I mean - you do not need inheritance relationship in you case, but something like aggregation or composition. For example your type of relations breaks The Liskov Substitution Principle.

BUT. Objective C accepts reverse relationships. You can use delegates (@protocol) to describe interfaces which can retrieve some data from unknown objects who accepts this @protocol.

So, in your case class B should conform a protocol which provide access to some properties of B. And A should be able to work with this protocol, i.e. to know getters which A needs.

SVGreg
  • 2,320
  • 1
  • 13
  • 17