views:

153

answers:

2

Hi, I'm writing an application which is quite graphically heavy and therefore I'm trying to implement a caching mechanism within my view controller that creates a view once, and retains it for future use, similar to the following:

- (UIView *)logoView
{
    if(_logoView == nil)
    {
        _logoView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"logo_header.png"]];
        _logoView.contentMode = UIViewContentModeCenter;
    }

    return _logoView;
}

This all works fantastically, however, I'm getting a bit confused over a certain issue; when I simulate a memory warning I call a method which purges the cache, like so:

- (void)purgeCachedContent
{
    if(_logoView != nil)[_logoView release];
}

However, this seems to be causing my application issues, as it can get called several times (dealloc, didReceiveMemoryWarning and viewDidUnload).

How can I determine if an instance exists to send it a release message? Even when I try to NSLog a released view I receive a EXC_BAD_ACCESS error, so I'm having trouble figuring out the best way I'd do it. I even removed the if statement hoping to rely on being able to send nil objects messages, but this causes the same error...

I'm sure it's something simple missing from my objective-c knowledge... I just don't know what!

+3  A: 

_logoView isn't set to nil automatically just by releasing it, so any future methods you try to call using that pointer will go to a memory location that used to contain a valid object, but now contains junk. You can fix this by setting _logoView = nil; after releasing it.

Marc Charbonneau
A: 

If you want to cache it why would you want to release it?

just use autorelease on init:

_logoView = [[[UIImageView alloc] initWithImage: [UIImage imageNamed: @"logo_header.png"]] autorelease];
carnz