使用Parse PFQuery构建一个简单的tableview

时间:2015-08-22 18:05:31

标签: ios objective-c uitableview parse-platform pfquery

您是使用Parse的新手,我正在尝试使用Parse PFQuery检索的数据加载一个简单的表视图控制器。虽然我可以在视图中加载“类别”数组,但是当代码到达numberOfRowsInSection时,数组似乎已被重置为nil。 任何有关这方面的帮助将不胜感激。 顺便说一句,我确实尝试将代码加载到带有文字的数组中,没有问题,表格显示正常。 下面是代码:

@implementation DisplayCategoriesTVC

NSArray *categories;

- (void)viewDidLoad {
    [super viewDidLoad];

    // CODE TO RETRIEVE CONTENTS OF THE PARSE CATEGORIES CLASS

    PFQuery *query = [PFQuery queryWithClassName:@"Categories"];
    //    [query whereKey:@"Sequence" > @1];
    [query findObjectsInBackgroundWithBlock:^(NSArray *categories, NSError *error) {
        if (!error) {
            // The find succeeded.
            NSLog(@"Successfully retrieved %lu categories.", (unsigned long)categories.count);
        } else {
            // Log details of the failure
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
       return [categories count];
}

我遇到的具体问题是,为什么numberOfRowsInSection是显示nil值的categories数组?

我遇到的具体问题是为什么categories数组现在显示为nil,我该怎样做才能保留PFQuery加载的值并在其他方法中使用它们?

1 个答案:

答案 0 :(得分:1)

您正在后台线程上执行某些操作:

findObjectsInBackground:

这是什么意思,因为你是新手?

What's the difference between synchronous and asynchronous calls in Objective-C, versus multi-threading?

那么,当您的数据最终从后台任务聚合时,您如何reload the tableView

您只需重新加载tableView,但我们需要在主线程上执行它,因为UI更新发生在那里:

[self.tableView reloadData];

有关详细信息,请参阅:

iPhone - Grand Central Dispatch main thread

完全如此:

PFQuery *query = [PFQuery queryWithClassName:@"Categories"];
//    [query whereKey:@"Sequence" > @1];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        // The find succeeded.
        NSLog(@"Successfully retrieved %lu categories.", (unsigned long)categories.count);
        self.categories = objects;
        //Since this is a UI update we need to perform this on the main thread:
        dispatch_async(dispatch_get_main_queue(), ^{
          [self.tableView reloadData];
        });
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

您的查询已在UI更新之前完成其任务,因为它在后台线程上发生,因此您需要告知UI组件何时完成。