views:

37

answers:

2

In my code, I use a singleton object as a central point in my app to load and cache images the app frequently needs, so I don't have to do resource-intensive memory allocation each time I load an image.

But there are times during the execution of my app where memory usage gets intense and I would like to release the cached image data. Currently, I'm just releasing the UIImage instances from my singleton when I get a memory warning.

I would prefer, however, to be able to release the entire singleton object. Is that possible? If so, how?

A: 

Any object you create you can just release at any time. (Presuming you create it and set it's properties.)

self.myObject = [[myObjectClass alloc] init];
    // do something with the object
   [self.myObject release];       // anytime that you are not using the object

self.myObject = nil; // will also work if you've set the @property (retain, nonatomic)
joelm
Are you sure that applies to singleton objects as well?
I am not. I don't see why it wouldn't, but don't know for sure.
joelm
A: 

Of course it is. Although it's rather likely that the memory usage of this object is negligible compared to the images.

By the nature of a singleton, you need to have an accessor for it, where you will create it if it does not currently exist:

+ (MySingletonClass*) mySingleton
{
    if ( mySingleton == nil )
    {
        mySingleton = [[MySingletonClass alloc] init];
    }

    return mySingleton;
}

You just need to add another that you call when you want to destroy it:

+ (void) destroyMySingleton
{
    [mySingleton release];
    mySingleton = nil;
}

If you keep references to it around elsewhere you'll have trouble; don't do that. If you access from multiple threads you'll need to synchronize. Otherwise, it's pretty straightforward -- the getter will recreate when you next need it.

walkytalky
Cool, thanks! You're right about the really low memory usage of the singleton, but I find it less confusing to just write `[mySingleton release]` instead of creating a new method like `[mySingleton releaseImageData]`
@ryyst Well, you still need to write a new method -- the class `destroy` method. I suppose you *could* hack it such that `dealloc` resets the static singleton to `nil`, but that would be really nasty.
walkytalky