1

我想将 Parse 查询中的 PFObjects 保存在我的班级称为 listdata 的 NSMutableArray 中。稍后我将使用 listdata 数组。当我跟踪我的代码时,它为找到的每个对象更新了 highScoreObjects 数组。但是当我尝试将 listdata 数组设置为 highScoreObjects 数组时,highScoreObjects 数组为空。有没有办法在查询结束后保留​​数据?

NSMutableArray *highScoreObjects = [[NSMutableArray alloc] initWithCapacity:5];

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // The find succeeded.
            NSLog(@"Successfully retrieved %d scores.", objects.count);
            // Do something with the found objects
            for (PFObject *object in objects) {
                [highScoreObjects addObject:object];
                NSLog(@"%@", object.objectId);
            }
            dispatch_async(dispatch_get_main_queue(), ^ {
                [self.tableView reloadData];
            });
        } else {
            // Log details of the failure
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];

self.listData = highScoreObjects;

我还尝试将线路保持self.listData = highScoreObjects;self.listData = highScoreObjects;循环内。这没有任何区别。

4

2 回答 2

2

并不是没有设置。就是还没设置。这是因为您正在使用findObjectsInBackgroundWithBlock并且异步过程尚未完成。

将您的分配 ( self.listData = highScoreObjects;) 移到块中,就在您发送重新加载表视图的请求之前。

于 2013-11-19T20:40:05.060 回答
0

这是不了解异步编程本质的又一个案例。

考虑这种情况:

你想做一个鸡蛋三明治。你把鸡蛋煮沸,并在它们煮熟时设置警报,以便将它们取出、剥皮、切碎并添加到三明治中。当你等待时,你得到面包和黄油,然后等待警报响起。

你的电话findObjectsInBackgroundWithBlock是把鸡蛋煮沸。您通过的街区是警报,以及您打算如何处理煮熟的鸡蛋。

您上面的代码类似于将鸡蛋煮沸,然后立即尝试在三明治上使用未煮过/半熟的鸡蛋。弄得一团糟。

解决方案是在您传递给该方法的块的末尾调用一个方法。

于 2013-11-21T22:33:51.833 回答