views:

64

answers:

2

If I declare a variable within a block (see below) is there a way to specify that its visible outside the block if need be?

if(turbine_RPM > 0) {
    int intResult = [sensorNumber:1];
    NSNumber *result = [NSNumber numberWithInt:intResult];
}
return result;

or is the way just to declare outside the block scope?

NSNumber *result = nil;
if(turbine_RPM > 0) {
    int intResult = [sensorNumber:1];
    result = [NSNumber numberWithInt:intResult];
}
return result;

many thanks

gary

+4  A: 

You need to declare the variable outside of the block. Code blocks determine scope.

Jasarien
A: 

I love one-liner:

return (turbine_RPM > 0) ? [NSNumber numberWithInt:[sensorNumber:1]] : nil;

As pointed out by Jasarien, you want to declare the variable outside the block. Or just return the NSNumber immediately.
The problem with your second example is that you will return an initialized variable if the if-statement fails, so you'd need to return something in an else-statement.

bddckr