如何在本地NSArray中保存查询结果?

时间:2014-09-10 06:16:34

标签: ios objective-c

我试图将从PFQuery获得的对象数组存储到本地NSArray中。我试图在内部执行if(!error)但它不会离开块,一旦块终止,所以在我的数组上执行它的值。

 @interface InstallersDirectoryTVC ()

 @property (nonatomic,strong) NSArray *installerName;
 @property (nonatomic, strong) NSArray *supervisors;


 @end

 //more code goes here
- (void)viewDidLoad
{
      [super viewDidLoad];


   PFQuery *query = [PFQuery queryWithClassName:@"InstallersInfo"];
   [query whereKey:@"supervisor" equalTo:@"yes"];
   [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        if (!error) {
            for (PFObject *object in objects) {
                self.supervisors = [objects valueForKey:@"supervisor"];
            }


    }else {
        NSLog(@"Error, %@ %@",error,[error userInfo]);
    }


}];

一切都在块内部工作,比如self.supervisors.count或NSLog,但它根本不会留下块。你能告诉我如何获得这些价值观吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试以下代码

__weak InstallersDirectoryTVC *weakSelf = self;

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        if (!error) {
            for (PFObject *object in objects) {
                weakSelf.supervisors = [objects valueForKey:@"supervisor"];
            }


        }else {
            NSLog(@"Error, %@ %@",error,[error userInfo]);
        }


    }];

答案 1 :(得分:0)

您必须使用NSMutableArray并在块之前初始化它。此外,对于数组中的每个PFObject,您只需将其分配给supervisor变量。您必须使用addObject:将其附加到数组中。你也有一个拼写错误,你试图使用valueForKey:对象数组而不是迭代中的当前对象。

@interface InstallersDirectoryTVC ()

 @property (nonatomic,strong) NSArray *installerName;
 @property (nonatomic, strong) NSMutableArray *supervisors;


 @end

 //more code goes here

// initialize the supervisors array in an init method

- (void)viewDidLoad
{
   [super viewDidLoad];   

   PFQuery *query = [PFQuery queryWithClassName:@"InstallersInfo"];
   [query whereKey:@"supervisor" equalTo:@"yes"];
   [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        if (!error) {
            for (PFObject *object in objects) {
                [self.supervisors addObject:[object valueForKey:@"supervisor"]];
            }


    }else {
        NSLog(@"Error, %@ %@",error,[error userInfo]);
    }


}];