title: iOS Design Pattern memory management with delegate and parent object
body: <p>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:</p>
  
  <p>MainView</p>
  
  <p>|_PageView</p>
  
  <p>|_CustomButton</p>
  
  <p>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</p>
  
  <pre><code>{
  CustomButton *customButton_ = [[CustomButton alloc] initWithFrame:CGRectMake(100.0,50+(i*55.0),200.0);
  customButton.delegate = self;
  [self addSubView:customButton_];
  [customButton_ release];
  }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>[pageView_ removeFromSuperview];
  [pageView release], pageView_ = nil;
  
  pageView_ = [PageView alloc] initWithFrame.....];
  </code></pre>
  
  <p>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) ?</p>
  
  <p>Right now i'm doing:</p>
  
  <p>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").</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>Thank you guys, im going overload with this problem and my brain is stuck in a close road. :)</p>