简体   繁体   中英

iOS Design Pattern memory management with delegate and parent object

Im struggling to solve in a very clean way a problematic involving memory overload (management). Im having a serie of view that include other views, in my project I have a situation like this:

MainView

|_PageView

|_CustomButton

soo far soo good, easy as a cake. CustomButton have a delegate (protocol) in it for some reasons, so we have in PageView a "for cycle" that creates N CustomButtons, set the delegate as self in PageView (PageVew extend CustomButtonDelegate) and release the buttons afer attaching them like

{
CustomButton *customButton_ = [[CustomButton alloc] initWithFrame:CGRectMake(100.0,50+(i*55.0),200.0);
customButton.delegate = self;
[self addSubView:customButton_];
[customButton_ release];
}

soo far soo good again. Button will be press, PageView get the protocol method, do some code and voilà, done. One problem is that at one point, MainView must remove PageView, so In a method I call

[pageView_ removeFromSuperview];
[pageView release], pageView_ = nil;

pageView_ = [PageView alloc] initWithFrame.....];

and I recreate the object with other data to display. I noticed that PageView never gets release and removed from the memory because its retainCount is exactly how many CustomButton I created inside PageView and assign the delegate to self plus one of course. My question is, what is the cleanest way to remove safely all the objects and be able to remove PageView too, free the memory (because Im loading a quite large amount of data to display in it) ?

Right now i'm doing:

Create in PageView a NSMutableArray, that I CustomButton the objects in it, and before to remove PageView, I cycle it and set the delegate = nil and then release each object, after I release the NSMutableArray (called "holder").

But the problem is that if I want to add more objects of different types with other protocols, adding to this array, can lead to other problems of retaining the objects.

Where do I lack guys, knowledge so I need to study more (quite sure I can say) or do I need to approach with another OOD?

Thank you guys, im going overload with this problem and my brain is stuck in a close road. :)

Looks like your CustomButton 's delegate is a retain property of CustomButton . Delegate should be an assign property, not retain nor copy . See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM