开发者

issue about subview retain superview in objective-C

开发者 https://www.devze.com 2023-01-20 13:39 出处:网络
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.

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开发者_JAVA百科!

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


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.


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号