views:

185

answers:

4

Hi, Does anyone know if the following code could be problematic:

NSString *addchar = nil;

if (case1)
addChar = [[firstname substringToIndex:1] capitalizedString];
else
addChar = [[fullname substringToIndex:1] capitalizedString];

Assume that firstname and fullname aren't null or empty. Does initializing the NSString object and setting it to 'nil' cause some possible problem? It seems to cause my app to freeze, but only for a very few users, and only those users, but it doesn't have anything to do with different input strings or empty strings. So I'm trying to isolate the problem, but I don't know the difference between

NSString *addChar;

and

NSString *addChar = nil;

Thanks.

+1  A: 

There is no difference here since you don't read addChar in your code. Moreover, the compiler may sometimes initialize addChar to nil for you if you don't do it explicitly (depending on the scope of addChar's declaration).

See related question at this place.

Romain
What the compiler will initialize it to isn't defined. In practice, it will be random garbage.
Chuck
Yep, I realized my formulation was not absolutely clear... It actually depends on the scope of the variable (there are cases where it's guaranteed to be initialized).
Romain
+5  A: 

Either form is perfectly acceptable. The problem you're having is elsewhere. I recommend doing some code profiling with Instruments to figure out where this issue is occurring.

Joshua Nozzi
Thanks. This is frustrating because I can't reproduce the problem myself (it's with an app I have) and it only affects a small group, and it doesn't cause a crash... it only hangs ... so it doesn't generate a crash log. So I don't know how else to track it down. Even Apple's engineers can't seem to find the problem.
z s
Does it matter if this code is running within a static method?
z s
+3  A: 

Without the nil initializer, in some cases your variable may be initialized with garbage (whatever was in the memory space previously). There are specific rules regarding which types of variables (scope-based, static storage, etc.) are nil-initialized automatically for you, but I've always found that it's easier to explicitly initialize all variables instead of memorizing those rules.

That said, because both branches of your if statement clobber any previous value of addChar, there should not be any case in which you can see an invalid value. But it's certainly not hurting anything to explicitly initialize to nil, and if a future maintainer comes along and changes the code paths you might find that the initializer saves you!

Steven Schlansker
+1  A: 

You should always initialize to nil if variable is not initialized otherwise.

You can send messages to nil they will be ignored.

NSString * str = nil;
NSLog(@"%@", [str description]);

Outputs:

2009-12-15 08:59:03.352 x[11775] (nil)

Of course I don't need to call description explicitly, I'm just demonstrating call to nil.

stefanB