Cocoa memory management

Posted by silvio on Stack Overflow See other posts from Stack Overflow or by silvio
Published on 2010-06-17T17:20:01Z Indexed on 2010/06/17 17:23 UTC
Read the original article Hit count: 497

At various points during my application's workflow, I need so show a view. That view is quite memory intensive, so I want it to be deallocated when it gets discarded by the user. So, I wrote the following code:

- (MyView *)myView {
    if (myView != nil)
        return myView;

    myView = [[UIView alloc] initWithFrame:CGRectZero]; // allocate memory if necessary.
    // further init here

    return myView;
}

- (void)discardView {
    [myView discard];   // the discard methods puts the view offscreen.
    [myView release];   // free memory!
}

- (void)showView {
    view = [self myView];
    // more code that puts the view onscreen.
}

Unfortunately, this methods only works the first time. Subsequent requests to put the view onscreen result in "message sent to deallocated instance" errors. Apparently, a deallocated instance isn't the same thing as nil. I thought about putting an additional line after [myView release] that reads myView = nil. However, that could result in errors (any calls to myView after that line would probably yield errors).

So, how can I solve this problem?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cocoa