简体   繁体   中英

What is the best way to initialise a variable in objective c, before a conditional statement?

I used to initialise variables before a conditional statement in the following way:

NSString *string = [[NSString alloc] init];
if (conditional statement) {
   string = @"foo";
}
else{
   string = @"bar";
}

But the Xcode Analyser complains:

"Value stored to 'string' during its initialization is never read"

So, I then tried a couple of different options:

A:

NSString *string = nil;
if (conditional statement) {
   string = @"foo";
}
else{
   string = @"bar";
}

B:

NSString *string = @"bar";
if (conditional statement) {
   string = @"foo";
}

So my question is, what is the best way to initialise a variable in objective c, before a conditional statement?

UPDATE:

The variable itself is not used [read] in the conditional. Here is an example below...

NSString *string = [[NSString alloc] init];
if (x == 0) {
   string = @"foo";
}
else{
   string = @"bar";
}

UPDATE:

Based on Sven's answer, it seems like a good compromise is:

NSString *string;
if (x == 0) {
  string = @"foo";
}
else{
  string = @"bar";
}

A and B are both valid options. In the end it won't really matter, if you just assign string literals. The compiler might even generate the same code for both cases.

Of course if you assign something other than compile-time constants you need to be more careful. Depending on the side effects that happen in your computation only one or the other version will be correct.

In your case A you won't even have to nil-initialise the variable at first, the compiler is smart enough to see that it is initialised in any case. For patterns like this where you want to initialise an variable depending on some conditions it's actually a good idea to skip the initialisation where the variable is defined. Then the compiler can produce a warning if there is a code path where you forgot to initialise the variable.

Another option for this is to use the ternary operator ?: :

NSString *string = condition ? @"foo" : @"bar";

This is not just shorter to write, but also makes it immediately clear that the variable is initialised no matter what the condition is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM