2014-09-11 54 views
0

我已經問了這個問題幾次,並沒有在解決這個問題上取得任何成功。所以我改進了我的代碼。我正在嘗試創建一個NSMutableArray並將Parse中的數據存儲在其中。然後我試圖在屏幕上顯示NSMutableArray。當NSLog在塊內時,我能夠顯示文本,但當它位於塊外部時,不能。請幫忙,因爲我一直在努力爲什麼我不能訪問塊外的NSMutableArray。感謝您的幫助提前。從解析塊外顯示NSMutableArray

//.h file 
#import <UIKit/UIKit.h> 

@interface IncomeTransactionViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> 
{ 
    NSMutableArray *accountArray; 
} 

@property (strong, nonatomic) NSMutableArray *accountArray; 

@end 


//.m file 
#import "IncomeTransactionViewController.h" 
#import <Parse/Parse.h> 

@interface IncomeTransactionViewController() 

@end 

@implementation IncomeTransactionViewController 

@synthesize accountArray; 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    accountArray = [[NSMutableArray alloc]init]; 
    PFQuery *query = [PFQuery queryWithClassName:@"Account"]; 
    [query whereKey:@"user" equalTo:[PFUser currentUser]]; 
    [query orderByDescending:@"startingBalance"]; 
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 

     for (PFObject *object in objects) { 
      [accountArray addObject:object[@"name"]]; 
     } 

     for (NSString *obj in accountArray) { 
      NSLog(@"Inside Block %@",obj); 
     } 
    }]; 


    for (NSString *obj in accountArray) { 
     NSLog(@"Outside Block%@",obj); 
    } 
} 

回答

0

發生這種情況的原因是因爲首先調用「外部塊」代碼,然後發生findObjectsInBackground。因此,在調用「外部塊」代碼時,您的NSMutableArray不會被填充。我不確定爲什麼你想把它放在塊之外?只需將代碼中剩餘的代碼放在塊中的主線程上即可。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
//this happens first 
    accountArray = [[NSMutableArray alloc]init]; 
    PFQuery *query = [PFQuery queryWithClassName:@"Account"]; 
    [query whereKey:@"user" equalTo:[PFUser currentUser]]; 
    [query orderByDescending:@"startingBalance"]; 

    //this happens third 
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 

     for (PFObject *object in objects) { 
      [accountArray addObject:object[@"name"]]; 
     } 

     for (NSString *obj in accountArray) { 
      NSLog(@"Inside Block %@",obj); 
     } 
    }]; 

//this happens second...note that accountArray is empty at this point 
    for (NSString *obj in accountArray) { 
     NSLog(@"Outside Block%@",obj); 
    } 
}