views:

222

answers:

2

I have these two pieces of code. The first one works perfectly:

UIView *tmp = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 60.0f, 296.0f, 44.0f)];
[self.dynamicView addSubview:tmp];
[tmp release];

The second one is pretty much the same, but the view doesn't show up.

CommentBox *commentBox = [[CommentBox alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 296.0f, 44.0f)]; 
[self.dynamicView addSubview:commentBox];
[commentBox release];   // Why does this remove the view?

If I remove the [commentBox release] the view surprisingly appears. But I don't see a different between these two code snippets.

The init for the CommentBox looks like this:

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Load the nib:
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
        self = [nibObjects objectAtIndex:0];

    }
    return self;
}
+1  A: 

You're doing weird things in -initWithFrame:. I'm not 100% sure that it's causing the problem you report, but I'm pretty sure it's:

  • wrong; and
  • causing a memory leak.

I don't think replacing a view object with something dearchived from a nib in its -init… methods is a good idea. Either load the nib from a controller class, or have your initialiser load the object's subviews from the nib without replacing self.

Graham Lee
Thanks Graham. I posted my new solution below.
znq
+1  A: 

After thinking about Graham's answer I came up with the following solution:

  1. I drag a new UIView (-> lets call it sub UIView) in Interface Builder in my main UIView
  2. I give this sub UIView the correct size (because I cannot resize the main UIView, which is always 320x460)
  3. I drag all my other elements in this sub UIView (so that all elements are attached to my sub UIView)
  4. I give my sub UIView a tag number (Interface Builder -> View Attributes), e.g. "300"
  5. In the code I do now the following within my -initWithFrame:

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil]; UIView *subView = [[nibObjects objectAtIndex:0] viewWithTag:300]; [self addSubview:subView];

Hope that helps.


Update:

I just had another idea of doing it. Instead of the tag numbers you can also create a IBOutlet UIView *viewHolder in the CommentBox class and set the outlet in IB. Then in the initWithFrame: I do the following:

[[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
[self addSubview:self.viewHolder];
znq