small medium large xlarge

Generic-user-small
23 Dec 2010, 14:52
Ric Levy (21 posts)

Hi Tim,

In chapter 7, we are asked to write the following code:

-(void)setStoredNumber:(float)newNumber
{
	storedNumber=newNumber;
}


-(float)storedNumber
{
	return storedNumber;
}

</code>

If I am understanding correctly, the first method decides what value “storedNumber” will hold, and the second method returns “storedNumber”. But how does the second method know the value of “storedNumber”? I thought the “scope” of variables meant that variables cease to exist after the final “}” of a method?

Thanks,

Ric.

Generic-user-small
27 Dec 2010, 17:16
Tim Isted (105 posts)

Remember to think of a variable as being valid for the scope in which it is declared.

If the @setStoredNumber:@ method had been written like this:

-(void)setStoredNumber:(float)newNumber
{
    float storedNumber = newNumber;
}

then the @storedNumber@ variable would only be valid up to the closing curly brace of the @setStoredNumber:@ method, because it is declared within this method.

The @storedNumber@ variable used in the book is an instance variable of a @WonderfulNumber@ object, and the variable is declared inside the @WonderfulNumber.h@ interface. This means each @WonderfulNumber@ object will “contain,” or have access to, its own @storedNumber@ variable for its entire object lifetime (from @init@ through to @dealloc@). So, the @setStoredNumber:@ and @storedNumber@ accessor methods can access that variable.

Look back over Section 5.3 “The Scope of a Variable”; this will also become clearer as you proceed through the rest of Chapter 7.

Generic-user-small
04 Jan 2011, 14:24
Ric Levy (21 posts)

OK I think I see… so if the variable is declared inside the header, it is available for the whole object, but if it is declared inside a method, it is only available for that method. Have I got that right?

Just coming back to the book after the Christmas break so hopefully I haven’t forgotten too much!

Generic-user-small
05 Jan 2011, 14:06
Tim Isted (105 posts)

Yes, if it’s inside the @interface in the header, it’s available for the whole object; if declared inside a code block (like a method), it’s available only for that code block.

In chapters 9 and 10, you’ll come across other types of code block for branching and looping (think of a code block as being anything between an opening and closing curly brace { and }. Again, any variable declared inside one of those blocks is only available inside such a block.

You must be logged in to comment