Smikey
Smikey

Reputation: 8236

How to declare an NSString with multiple possible values

I want to declare an NSString object to use within an alert, but its actual content depends on various factors, determined by some variable. I'm wondering how best to approach this. In most cases I've done something like this:

- (void)info {
    NSString *targetString = [[NSString alloc] init];
    switch (self.target) {
        case 1:
            targetString = @"ONE";
            break;
        case 2:
            targetString = @"TWO";
            break;
        case 3:
            targetString = @"THREE";
            break;
        default:
            targetString = @"";
            break;
    }

NSString *message = [[NSString alloc] initWithFormat:@"Text: %@", targetString]; 
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle:@"Info"
                          message:message 
                          delegate:self 
                          cancelButtonTitle:@"Ok!" 
                          otherButtonTitles:nil];
    alert.tag = kInfoAlert;
    [alert show];
    [alert release];
    [targetString release];
    [message release];
}

However when I run this through the build analyser, I get messages telling me the string is leaking memory:

First of all it says:

Value stored to 'targetString' during its initialization is never read

Then:

Potential leak of an object allocated on line 137 and stored into 'targetString'

These 2 comments are at line 136 and 137, where line 136 is

NSString *targetString = [[NSString alloc] init];

An alternative might be to declare the string as

NSString *targetString;

and set it in each case as

targetString = [NSString stringWithFormat:@"ONE"]; 

etc

Or even allocing the String in each case in order to release it at the end...

Well, what would be the best approach here?

Thanks,

Michael :)

Upvotes: 0

Views: 1747

Answers (3)

zoul
zoul

Reputation: 104065

How about this instead of the switch:

- (NSString*) stringForIndex: (NSUInteger) index
{
    NSParameterAssert(index < 4);
    id strings[] = {@"none", @"one", @"two", @"three"};
    return strings[index];
}

Upvotes: 0

kovpas
kovpas

Reputation: 9593

I believe this would be enough:

NSString *targetString = nil;

And you don't need to release targetString then.

Upvotes: 2

Joe
Joe

Reputation: 57179

The reason for your memory leak is because you are needlessly allocating a string with this line

NSString *targetString = [[NSString alloc] init];

and then setting it to a literal object. Define targetString as nil because when you set it to another value like targetString = @"ONE" you are no longer referencing the empty string you allocated and that causes a memory leak. As for your approach of the switch case for determining the value that is fine.

Upvotes: 5

Related Questions