我对 Parse 和 iOS 开发都是新手。基本上,我试图实现一种在一个类中检索解析对象的方法,其他类将使用实体名称调用该方法以返回对象。因此另一个类将使用 entityName
作为参数来调用 retrieveRecords
方法。
然而,数组总是返回 nil,因为 block 方法直到数组返回后才会执行。之前(当我获取对象起作用时!)我只有一个方法来检索我需要数据的同一类中的对象,因此我只声明了一个 __block 数组来返回数据。
我知道这是一个常见问题,因为我在谷歌上进行了广泛的搜索,但我似乎找不到将对象数组返回到另一个类的正确解决方案,并且最终得到了更多不起作用的困惑代码。
- (void)doQuery:(NSString *)entityName
{
//Create query for all Post object by the current user
PFQuery *workoutQuery = [PFQuery queryWithClassName:entityName];
[workoutQuery whereKey:@"owner" equalTo:[PFUser currentUser]];
// Run the query
[workoutQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
//Save results and update the table
NSLog(@"Adding objects to the array");
NSLog(@"Size %lu" , (unsigned long)objects.count);
//fill the array once the block is BEING EXECUTED
[self successfulRetrievedArray:objects];
}
}];
}
-(NSArray *)successfulRetrievedArray:(NSArray *)objects
{
self.objectsArray =[[NSMutableArray alloc]initWithArray:objects];
return self.objectsArray;
}
-(NSArray *)retrieveRecords:(NSString *)entityName
{
//DO QUERY
[self doQuery:entityName];
//RETRIEVE RECORDS
return self.objectsArray;
}
最佳答案
- (void)doQuery:(NSString *)entityName withCompletionBlock:(void (^)(NSArray *objects, NSError *error))completionBlock {
//Create query for all Post object by the current user
PFQuery *workoutQuery = [PFQuery queryWithClassName:entityName];
[workoutQuery whereKey:@"owner" equalTo:[PFUser currentUser]];
// Run the query
[workoutQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
//Save results and update the table
NSLog(@"Adding objects to the array");
NSLog(@"Size %lu" , (unsigned long)objects.count);
//fill the array once the block is BEING EXECUTED
[self successfulRetrievedArray:objects];
if (completionBlock) {
completionBlock(objects, nil);
}
} else {
if (completionBlock) {
completionBlock(nil, error);
}
}
}];
}
将您的代码替换为上面的代码。只需将带有数组的登录放入完成 block
关于ios - 重用findObjectsInBackgroundWithBlock方法: Array is nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22053914/