Perform action after findObjectsInBackgroundWithBl

2020-05-01 18:17发布

I have such construction in my code:

for (METMeetingEntity *e in self.meetingList) {
            PFQuery *query = [PFUser query];        
            //some query constraints, depending on METMeetingEntity
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
            {
                // some query actions


                NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
                self.meetingList = [NSMutableArray arrayWithArray:[self.meetingList sortedArrayUsingDescriptors:sortDescriptors]];
                self.meetingList = [self dateCleanup:self.meetingList];
            }];

How can I perform action - reload my table view after all the findObjectsInBackground are completed

2条回答
老娘就宠你
2楼-- · 2020-05-01 18:42

One possible solution would be to keep a count. When the number matches the original count, you know you are done.

NSUInteger count = self.meetingList.count;
for (METMeetingEntity *e in self.meetingList) {
    PFQuery *query = [PFUser query];        
    //some query constraints, depending on METMeetingEntity
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        // some query actions
        NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
        self.meetingList = [NSMutableArray arrayWithArray:[self.meetingList sortedArrayUsingDescriptors:sortDescriptors]];
        self.meetingList = [self dateCleanup:self.meetingList];

        count--;
        if (count == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // reload table or whatever needs to be done
            });
        }
    }];
}
查看更多
爷的心禁止访问
3楼-- · 2020-05-01 19:00

I think you don't need calling dispatch_async. All the blocks in Parse run in the main thread. In Parse doc you can read:

Both findObjectsInBackgroundWithBlock: and findObjectsInBackgroundWithTarget:selector: work similarly in that they assure the network request is done without blocking, and run the block/callback in the main thread.

This is an example of a query for a UICollectionView:

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if(!error) {
            listaFiguras = [objects mutableCopy];
            [_collectionView reloadData];
        } else {
            NSLog(@"Something wrong. No Data.");
        }
    }];
查看更多
登录 后发表回答