开发者

iPhone Objective-C memory leak issue

Im having a bit of an issue where i cr开发者_StackOverflow社区eate an array of button objects and place them onto a view, something like

for(int i=0;i<_number;i++) { 
    _object = [[object alloc]init];
    [self.view addsubview:_object];
}

However if i release them straight after i add them to the view, they break when the user taps on them naturally. My question is where would be the best place to release them?

The list is repopulated periodically so currently im keeping a reference to the objects and when i got to repopulate i release them there by iterating through the view like

for(_object *obj in self.view) { 
    [obj removeFromSuperview]; 
    [obj release]; 
}

Is there a more elegant way to do this?


The superview retains its subviews, so there is no need for you to retain them. Especially since you don't have references to the objects themselves (i.e. you are taking references from self.view) you shouldn't bother with the memory management of them.

There seem to be a few typos here so I assume you're not posting real code. (object vs _object)

The first for loop could look like:

for(int i=0;i<_number;i++) {
    _object = [[[Object alloc]init] autorelease];
    [self.view addsubview:_object];
}

The second one:

for( Object *obj in self.view.subviews ) {
    [obj removeFromSuperview];
}

(changed object to Object for clarity)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜