xanadu6291
xanadu6291

Reputation: 931

Objective-c refer variable outside of block

I'd like to refer variable which I define inside of if block at outside of if else block. How can I? If it can't be, do I have to write same long code (they can't be function or method) inside if block and else block?

if (aTrack.compilation)
{
    NSString *artistName = NSLocalizedString(@"compilations", @"");
}
else
{
    NSString *artistName = aTrack.artist
}

NSLog(@"%@",artistName);

Upvotes: 0

Views: 95

Answers (3)

Julian
Julian

Reputation: 9337

What @nickfalk and @CRD posted is good but you can also (for such easy statements) use a ternary operator which in this case will look like this:

NSString *artistName = aTrack.compilation ? NSLocalizedString(@"compilations", @""): aTrack.artist;

NSLog(@"%@",artistName);

It is a matter of style but I would go this way for this simple example as my code is in one line

Upvotes: 1

T. Benjamin Larsen
T. Benjamin Larsen

Reputation: 6383

This will do what you want:

NSString *artistName;

if (aTrack.compilation){
    artistName = NSLocalizedString(@"compilations", @"");
} else {
    artistName = aTrack.artist;
}

NSLog(@"%@",artistName);

Also have a look at CRD's reply as this is really basic knowledge and you really need to understand this. (Also, as viperking noticed in my example, there was a terminating semicolon missing in your original code...)

Viperking has a nice example using the the ternary operator. It might be a bit alien at first but is rather nice when you wrap your head around it. a third solution would be

NSString *artistName = aTrack.artist;

if (aTrack.compilation){
    artistName = NSLocalizedString(@"compilations", @"");
} 

NSLog(@"%@",artistName);

For more complex scenarios I would advice against it, but for an example with two possible cases and one single string it would be quite legible. I'd also advice using nil rather than an empty-string for the localizedString comment.

Upvotes: 0

CRD
CRD

Reputation: 53000

The lifetime of an ordinary (non static) variable declared in a block is just that block, any nested blocks, etc. This is part of the standard lifetime and visibility rules of (Objective-)C(++).

Just declare the variable before the if/else and assign values to it in each block.

Upvotes: 1

Related Questions