views:

56

answers:

3

Hi, here's a problem with memory management issue.

Say i have a view A, it has a pointer that points to its subview B. I use @property(nonatomic, retain) refer to the view B.

Now in subview B, i need a pointer to point back to its superview A. So i use another @property(nonatomic, retain) refer to its superview A.

Here's my concern, i've read an article Hold Me, Use Me, Free Me about retain and release stuff in objective c. It mentioned "retain cycles". So it says that a subview does not need to retain its superview, actually it would be redundant if it does so. Is that means in my example, the subview B only need to use @property(nonatomic) refer to its superview A? Thx!

BTW, if I didn't write retain in the @property for view A, do i need to [viewA release] in the dealloc method?

+3  A: 

Every subview already has a pointer to its superview. It is managed by the NSView class. See -[NSView superview]. So you can just use [self superview] or self.superview and ignore the memory management entirely.

If you want to continue as you are for whatever reason, you would need to specify that the superview property is an assign property to avoid a warning. You also would not release it in -dealloc because you have never retained it.

Put simply: subviews don't own their superviews.

If you're coding for iOS, just replace NSView with UIView and reread.

Jeremy W. Sherman
So what if View A is a UIViewController class(subclass of UIResponder->NSObject)? I tried to add a subview, which is a UIImageView(subclass of UIView). So when I use self.superview in the subview class, it didn't give me the UIViewController class(which i want), but gives me the UIViewController.view. So how could i do to get the UIViewController class. (Actually it's the UIViewController.view class addSubview of the UIImageView, not the UIViewController class itself. So in the subView class the self.superView didn't point to the UIViewController class)
JohnnySun
It pays to be exact: a view controller is not itself a view, but rather governs a view. A view is ignorant of its controller by design. Its communication with its controller is mediated by the responder chain: user interaction bubbles up the responder chain till it meets a handler. You can walk this chain yourself using `-[UIResponder nextResponder]`. Since a view controller owns its controlled view, you still need to be wary of causing a retain cycle - you still wouldn't want the subview to retain its superview's controller.
Jeremy W. Sherman
A: 

Now in subview B, i need a pointer to point back to its superview A.

You've already got one. Use [self superview].

NSResponder
A: 

Your UIView shouldn't need the UIViewController. What are you trying to do? If you haven't already, read Apple's docs on the Model-View-Controller style.

Peyman
My view is actually the ViewController's view, it's created automatically when i create the View-Based project.
JohnnySun