iPhone: [subview release] removes my subview from the display
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 lo开发者_高级运维oks 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;
}
After thinking about Graham's answer I came up with the following solution:
- I drag a new UIView (-> lets call it sub UIView) in Interface Builder in my main UIView
- I give this sub UIView the correct size (because I cannot resize the main UIView, which is always 320x460)
- I drag all my other elements in this sub UIView (so that all elements are attached to my sub UIView)
- I give my sub UIView a tag number (Interface Builder -> View Attributes), e.g. "300"
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];
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
.
精彩评论