Simple question about variable declaration


#1

Simple question: at the top of p. 198, the code for the AppController.m contains the line:

preferenceController = [[PreferenceController alloc] init];

But what would be wrong with replacing the line with:

PreferenceController *preferenceController = [[PreferenceController alloc] init];

Note that the last version causes the compiler to issue a warning about the “preferenceController” variable not being used, while in the version above, all is ok. This question came up before in an earlier post submitted in Ch. 6 on “Re: Challenge:Make a Data Source” by loumaag on Sun Nov 27, 2011 4:13 pm.

But Adam’s reply didn’t really answer the question, but rather, just said, “Aha. Glad you got it resolved! Look out for those compiler warnings.”

If I can understand this simple point than I will have learned something more about Objective-C.
Thanks!


#2

The reason that

if (!preferenceController) { PreferenceController *preferenceController = [[PreferenceController alloc] init]; }

yields the warning, “Unused variable ‘preferenceController’” is that when you have a line of code that starts: “ClassName *variableName”, you are creating a new variable, in this case on the stack. The preferenceController created on the stack in this case hides the instance variable preferenceController within the local scope. So once that if block is over, the stack variable you assigned a new instance of PreferenceController to is gone, and the instance variable preferenceController is unchanged (nil).

It’s a big no-no to create local stack variables that hide (shadow) instance variables by using the same name. This is why a lot of programmers use a prefix on their instance variables, such as _preferenceController or mPreferenceController.

Does this answer your question? If you are unclear on this, please say so.


#3

Hi Adam, yes, that helps a lot, thanks for the explanation!