从块外的Parse显示NSMutableArray

时间:2014-09-11 04:41:33

标签: ios objective-c

我已经问了几次这个问题,并没有成功解决这个问题。所以我改进了我的代码。我正在尝试创建一个NSMutableArray并将Parse中的数据存储在其中。然后我试图在屏幕上显示NSMutableArray。我可以在NSLog位于块内时显示文本,但是当它在块外时不显示。请帮忙,因为我一直在努力解决为什么我无法访问块外的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);
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}