简体   繁体   中英

iPhone Objective-C memory leak issue

Im having a bit of an issue where i create 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 (ie 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)

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