2014-05-06 45 views
-1

我試圖打印我用解析填充的數組的內容,但在函數之外數組爲空且打印爲空。我怎樣才能解決這個問題?感謝Array函數爲null

- (void) retrieveFromParse { 
PFQuery *retrieveColors = [PFQuery queryWithClassName:@"Bracciali"]; 

[retrieveColors findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 



     NSArray *array = [objects objectAtIndex:0];//Selects the first "object" from all the "objects" 
     array = [array valueForKey:@"NomeDispositivo"];//Makes a NSArray from the "pairs" values 
     colorsArray = [array mutableCopy];//Converts the array to a NSMutableArray 

     NSLog(@"%@", colorsArray); // PRINT THE ARRAY,,, 


    } 

}]; 


NSLog(@"%@", colorsArray); //PRINT NULL 

} 

回答

0

的問題是,findObjectsInBackgroundWithBlock是在後臺線程中運行(如果它的名字是什麼去了),所以當執行該語句:

NSLog(@"%@", colorsArray); //PRINT NULL 

此背景下「工作」不是招」完成(或者甚至可能開始)。

如果要安排一些事情發生,一旦findObjectsInBackgroundWithBlock已經完成,那麼你將需要用完成處理(另一個塊)爲它供給,並有findObjectsInBackgroundWithBlock呼叫,可能提供一個錯誤代碼來告訴我們,如果塊它成功與否。然後,您可以在完成處理程序中執行您的日誌記錄/其他任何事情。

0

應該

- (void) retrieveFromParse 
{ 
     PFQuery *retrieveColors = [PFQuery queryWithClassName:@"Bracciali"]; 

    __block NSArray *array = nil; 
    [retrieveColors findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) 
    { 
     array = [objects objectAtIndex:0];//Selects the first "object" from all the "objects" 
     array = [array valueForKey:@"NomeDispositivo"];//Makes a NSArray from the "pairs" values 
     colorsArray = [array mutableCopy];//Converts the array to a NSMutableArray 

     NSLog(@"%@", colorsArray); // PRINT THE ARRAY,,,  
    } 

}]; 


NSLog(@"%@", colorsArray); //PRINT NULL 

} 

在你的代碼中array對象的範圍是塊中。像上面那樣將array對象移動到塊之外。

應該工作!