Amazon.com Widgets Block variables not right on page 264
Welcome, Guest. Please login or register.
Did you miss your activation email?
November 23, 2014, 03:08:32 PM
Home Help Search chat Login Register 
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+ Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+ Old Stuff
| |-+ Chapter Study
| | |-+ Chapter 13 - Underlying C Language Features
| | | |-+ Block variables not right on page 264
Pages: [1] Go Down
Print
Author Topic: Block variables not right on page 264 (Read 636 times)
Trimakas
Newbie
*
Posts: 9






on: December 09, 2011, 10:22:21 AM

So here is my code..

Code: (Objective-C)
  
    __block int foo = 10;

    void (^printFoo) (void) =
    ^(void) {
    NSLog(@"foo = %i", foo);
    foo = 20;
     
    };

     foo = 15;
    printFoo();
    NSLog(@"foo = %i", foo);

But my output is
foo = 15
foo = 20

I can't make sense of it, because the book is telling me the output should be 10 & 20..

I understand the variable displayed for the block is what it was when the block was defined and not executed...

And I'm also assuming because the variable is a block variable it can only be changed within a block.. but mine seems to be getting changed outside the block.

What do you all think?
Logged
mitchb
Full Member
***
Posts: 144






Reply #1 on: December 09, 2011, 10:54:16 PM

The "__block" allows the variable to be changed inside the block. The first printFoo() prints 10 and changes the variable to 20. The second one prints 20, foo is then set to 15 and the third printFoo() prints 15 and resets foo back to 20.

Code: (Objective-C)
 __block int foo = 10;
    
    void (^printFoo) (void) =
    ^(void)
    {
        NSLog( @"Foo = %i", foo );
        foo = 20;
    };  

    printFoo();
    printFoo();
    
    foo = 15;
    
    printFoo();
Mitch
Logged

If you give a man a program, you will frustrate him for a day;
If you teach him how to program, you will frustrate him for a lifetime;
     - Anonymous
Pages: [1] Go Up
Print
Jump to:



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.