2015-04-22 68 views
0

新手問題...我試圖在代碼塊中設置變量self.projectName,但是當我在代碼塊外調用它時,值不會保留。在閱讀了關於代碼塊的更多內容之後,似乎有一些關於值何時可用的規則,但我仍然不清楚爲什麼我不能設置以後使用的值......任何幫助都將非常感謝!在代碼塊中設置的變量不保留其值

PFQuery *query = [PFQuery queryWithClassName:@"ScheduledProjects"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) { 
    if (!error) { 
     PFObject *project = [projects objectAtIndex:indexPath.row]; 
     self.projectName = project[@"name"]; 
    } else { 
     // Log details of the failure 
     NSLog(@"Error: %@ %@", error, [error userInfo]); 
    } 
}]; 

NSLog (@"project name = %@",self.projectName); 
+0

快,讓我們的財產是如何定義的。這可能是屬性「弱」或「分配」的問題。而且,塊之後的代碼(該塊是異步的)在塊完成之前運行,因此它還沒有值。 –

+0

瞭解異步處理。 – rmaddy

回答

0

該塊意味着異步調用,這意味着在您定義它之後,您不知道它何時會完成執行。 要使用該變量,請嘗試創建回調函數並在該塊的末尾調用它。你會知道它已經被執行。

例子:

-(void)yourMethod{ 

PFQuery *query = [PFQuery queryWithClassName:@"ScheduledProjects"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) { 
    if (!error) { 
      PFObject *project = [projects objectAtIndex:indexPath.row]; 
     self.projectName = project[@"name"]; 
     [self callback];//You call the method when your block is finished 
    } else { 
     // Log details of the failure 
     NSLog(@"Error: %@ %@", error, [error userInfo]); 
     //Here you could call a different callback for error handling (or passing a success param) 
    } 
}]; 

} 

-(void) callback{ 
    //Here you know the code has been executed 
    NSLog (@"project name = %@",self.projectName); 
} 
+0

總是有意義的。非常感謝你的幫助! – gumbynr