views:

42

answers:

1

xCode's "build and analyze" complains about "s" being possible garbage.

Which is the better solution? A, B, or C?

NSString *s;              // A
NSString *s = nil;        // B
NSString *s = @"";        // C

if(x == 1) s = @"you picked 1";
if(x == 2) s = @"you picked 2";
if(x == 3) s = @"you picked 3";
+2  A: 

I always go with

NSString *s = nil;

as a default initialization value. It's more sensible than an empty string (an empty string is a "thing", whereas nil is an unknown value), and since you can message nil in Objective-C it (generally) doesn't cause big problems if I somehow forget to give it a "real" value.

mipadi
nil is not unknown, it is very well defined. The empty string on the other hand also (probably) allocates memory. nil is the way to go.
Eiko
I mean to say that `nil` represents an unknown value, whereas an empty string is a known value.
mipadi
What will be the 'value' of `s` when initializing it like `NSString *s;` ? Will it just be `nil`, like with ivars that haven't been manually assigned a value, or will it be something else?
Douwe Maan
It'll be garbage. In Obj-C, instance vars are automatically initialized to `nil`, but local vars point at areas of memory that likely have no meaningful values.
mipadi
Sounds like "set it to nil" is the way to go. Does that also apply for NSMutableString used in the same way as above?
Annette