2013年7月6日 星期六

Block的使用2-注意事項

文章攢寫時間︰2013/07/07 14:33

Block使用注意事項

前一面提到Block的使用,
這裡提到一點蠻特別、而且也可能在日後造成程式BUG的地方

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    ViewController *myView = [ [ViewController alloc] init];
    myView.delegate = self;
    [myView willCallDelegatePrint];
    [myView willCallDelegateLog:@"Hello myDelegate"];
        NSLog(@"sub viewDidLoad");
    
    int outsideValue = 123;
    
    int (^myBlock)(int, NSString*) = ^(int num, NSString* str)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"I am Title" message:str delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Btn1" , nil];
        [alert show];
        
        //Block對外面的值只能是ReadOnly
        return outsideValue;
    };
    
    outsideValue = 456;
    NSLog(@"get int: %d",myBlock(567,@"白七")); 
    
}
 

如果以程式的先打先執行概念來看,
因為myBlock在outsideValue=456之後才呼叫,
NSLog應該會印岀outsideValue為456,
但是,卻印岀值為123

以下是執行的結果

Block只會使用變數第1次宣告時的值。

如果希望印出來是456,
那麼outSideValue在宣告時,
前面要加上__block關鍵字。
以下是修改後的Code︰

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    ViewController *myView = [ [ViewController alloc] init];
    myView.delegate = self;
    [myView willCallDelegatePrint];
    [myView willCallDelegateLog:@"Hello myDelegate"];
        NSLog(@"sub viewDidLoad");
    
    __block int outsideValue = 123;
    
    int (^myBlock)(int, NSString*) = ^(int num, NSString* str)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"I am Title" message:str delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Btn1" , nil];
        [alert show];
        
        //Block對外面的值只能是ReadOnly
        return outsideValue;
    };
    
    outsideValue = 456;
    NSLog(@"get int: %d",myBlock(567,@"白七")); 
    
}
 
結果如下

相關文章︰

1. Block的使用1
2. Block的使用3-typedef的使用

沒有留言 :

張貼留言