UIImage release or not release?


#1

On page 135 we create an UIImage from file. I think we should release it

if (self) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@“Hypnosis”];

    // Create an UIImage from a  a file
    UIImage *i = [UIImage imageNamed:@"Hypno.png"];
    
    // Put the image  on the tab bar item
    [tbi setImage: i];
    
    [i release];

}

Is this unnecessary ?

Ciao


#2

You should not release the image in this code; it could cause your program to crash. A helpful term to remember when you are working with manual reference counting is NARC - New, Alloc, Retain, Copy. If you initialize an object and it has one of these terms (and copy is anything with copy, such as mutableCopy), then the object has a reference count of 1. Anything else is autoreleased, meaning it currently has a reference count of 1, but it will be automatically released at the end of the current run loop.

For example, we can take a look at this example, using NSString.

NSString *str = [[NSString alloc] initWithString:@"Hello, World"]; // This has alloc, so it's reference count is 1, so we need to release after we are done with it. [[self tabBarItem] setTitle:str]; // We are done with it now [str release];
On the other hand,

NSString *str = [NSString stringWithString:@"Hello, World"]; // No new, alloc, retain, or copy, so this is autoreleased [[self tabBarItem] setTitle:str]; // We are done with it here, but no need to release, as it will be autoreleased at the end of the current run loop

Let me know if you need me to clarify anything.


#3

Got it.

I like the NARC stuff :slight_smile: easy to remember. Thanks!!
Ciao