使用 Parse PFQuery 构建一个简单的表视图

Building a simple tableview using Parse PFQuery

大家好,我是使用 Parse 的新手,我正在尝试加载一个简单的 Table 视图控制器,其中包含使用 Parse PFQuery 检索的数组中的数据。虽然我可以 nslog 视图中的 "categories" 数组确实加载了,但当代码到达 numberOfRowsInSection 时,该数组似乎已重置为 nil。 对此的任何帮助将不胜感激。 顺便说一句,我确实尝试过将代码加载到带有文字的数组中,没问题 table 显示正常。 代码如下:

@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 值?

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

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

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 组件。