Say I want to create an instance of NSString, which is initialized to a certain value depending on the value of another variable. Normally, I would do
NSString *string;
if(foo == 1)
string = @"Foo is one.";
else
string = @"Foo is not one.";
However, in some sample code that I’ve seen, I’ve seen people do
NSString *string = nil;
if(foo == 1)
string = @"Foo is one.";
else
string = @"Foo is not one.";
What is the difference between these two, and which method is preferred?
My personal preference is to initialize any variable immediately. However, in the sample you provided, these two methods are equivalent.
In
Clanguages (i.e.C,C++,Obj-C) variables that are not initialized immediately may contain random garbage values. Using the the variable before it is initialized lead to unexpected behavior (ranging from hopefully crashing to getting unexpected behavior).Example
Consider the following example:
Here the code leaves
absvariable uninitialized ifargumentis 0. So you would getting random values logged and then lead to corrupting the values in the rest of the program; and it would be hard to detect where the problem is!If you use an uninitialized reference, you would most likely get a
EXC_BAD_ACCESS.