开发者

Memory leak warning on release but not on autorelease

I have a problem with memory leak warning when releasing an object after returning it. I read a few posts about the similar subject but in those posts problem with releasing was that in the end "they" didn't really own the objet they were releasing.

If I use autorelease while initializing that same object I get no problems. My question is: if Apple suggests releasing manually all the objects that we created, how come I get this warnings?

- (UITableViewCell *)tabl开发者_如何学PythoneView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

    //Display no cells until it loads
    if([items count] < numberOfItemsToDisplay){

        UITableViewCell *cell = [[[UITableViewCell alloc] init]autorelease]; 
        return cell;
        //[cell release];

    }

I have no problems autoreleasing objects but I hate not understanding things I thought I understood :)

Thanks, L


Apple don't say "manually release all the objects you create" -- they just say "release eventually all the objects you create". That can be done by a manual release or by an autorelease.

An autorelease is basically just a manual release that occurs at some later point (at the point [NSAutoreleasePool drain] or [NSAutoreleasePool release] gets called).

If you want one of your methods to return an object that is owned by the caller, you have to use autorelease because if you call release before your 'return' and the retain count goes does to zero (which it usually will if you've just made the object) then the object will immediately be dealloc'd and then unusable. The caller of the method finds themselves with a pointer to some garbage non-object.


After return statement function is returned and nothing further is executed. So release after return will not execute. So you will leak memory. And you can not release before the return as the caller will use that object. So you really can't release that before return. So you have two ways to handle this situation. 1st option is to make the returned object autorelease. Another option is to make the function name in such a way that the caller know that it owns the returned object and must release it.

Check Returning Objects from Methods from Memory Management Programming Guide for the details explanation of this case.


When you return cell u do not own the object after that point and hence u cannot release it. When the return statement is executed the functions returns to the point from where it was called. So the statements after the return is not executed. So when u release the cell after the return its not executed which means the cell is not released. Hence it causes a memory warning.


Add a UitableView class in xcode and it will automatically add delegates correctly for the reuse of tableviewcells.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜