Search code examples
iosparse-platformnsmutablearraypfquery

Insert object on parse in my table


I have a view controller with inside table and I want to fill her with an array saved on Parse. To download the data I use this code:

 PFQuery *query = [PFQuery queryWithClassName:@"myClass"];
[query whereKey:@"X" equalTo:@"Y"];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    if(error==nil){

       myArray=[object objectForKey:@"Z"];
       NSLog(@"%@",myArray);
    }

}];
}

Now I display it inside myarray the data on parse. But if I use arrays to populate the table it is always me empty. I used NSLog and I saw that outside of the method [query getFirstObjectInBackgroundWithBlock: ^ (PFObject * object, NSError * error) my array is always empty. How can help me?


Solution

  • Fetching data from a remote database takes a little time. The parse functions that take block params run asynchronously. See the comments within your slightly modified code...

    [query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if(error==nil){
           // this appears first in the file, but runs later
           // after the request is finished
           myArray=[object objectForKey:@"Z"];
           NSLog(@"%@",myArray);
           // tell our view that data is ready
           [self.tableView reloadData];
        }
    }];
    
    // this appears second in the file, but runs right away, right
    // when the request is started
    // while execution is here, the request isn't done yet
    // we would expect myArray to be uninitialized
    

    Be sure, in your datasource methods e.g. numberOfRows to answer myArray.count. And use the data in the array myArray[indexPath.row] when building the table view cell.