ios - 重用findObjectsInBackgroundWithBlock方法: Array is nil

标签 ios objective-c-blocks parse-platform

我对 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/

相关文章:

ios - 从 json 文件创建 NMARoute 对象,无需额外的 HTTP 调用

ios - 延迟后如何触发 block ,例如 -performSelector :withObject:afterDelay:?

ios - 如何在 AppDelegate 中使用 Parse 正确设置 Facebook iOS SDK?

ios - 访问 NSError.localizedDescription 时偶尔崩溃

ios - 减少解析 Collection View 中的加载时间

ios - 数组中的 Swift 闭包在 Objective-c 中变为 nil

ios - 如何使用两个 NSRedcate 过滤 NSArray

ios - cellforRowAtIndexPath 效率如何?

ios - 将代码块分配给属性 objective-c

ios - 我正在努力实现 UIDynamicBehavior 的子类