0

我正在尝试在加载视图时初始化从 parse.com 获取的几个属性,以便我可以对它们进行计算。例如,我在头文件中声明以下内容:

TaskViewController.h

@property (nonatomic, assign) int taskTotalCount;
@property (nonatomic, assign) int taskCompletedCount;
@property (nonatomic, assign) int progressCount;


- (void)CountAndSetTotalTask;
- (void)CountAndSetCompletedCount;
- (void)CalculateProgress;

然后在实现中,假设所有其他初始化都正确设置并在 viewdidload 中调用,以下是方法实现:

TaskViewController.m

- (void)CountAndSetCompletedCount {
    // Query the tasks objects that are marked completed and count them
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    [query whereKey:@"Goal" equalTo:self.tasks];
    [query whereKey:@"completed" equalTo:[NSNumber numberWithBool:YES]];
    [query countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
        if (!error) {

            // The count request succeeded. Assign it to taskCompletedCount
            self.taskCompletedCount = count;

            NSLog(@"total completed tasks for this goal = %d", self.taskCompletedCount);

        } else {
            NSLog(@"Fail to retrieve task count");
        }
    }];

}

- (void)CountAndSetTotalTask {
    // Count the number of total tasks for this goal
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    [query whereKey:@"Goal" equalTo:self.tasks];
    [query countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
        if (!error) {

            // The count request succeeded. Assign it to taskTotalCount
            self.taskTotalCount = count;

            NSLog(@"total tasks for this goal = %d", self.taskTotalCount);
        } else {
            NSLog(@"Fail to retrieve task count");
        }
    }];
}

- (void)CalculateProgress {
    int x = self.taskCompletedCount;
    int y = self.taskTotalCount;
    NSLog(@"the x value is %d", self.taskCompletedCount);
    NSLog(@"the y value is %d", self.taskTotalCount);
    if (!y==0) {
        self.progressCount = ceil(x/y); 
    } else {
        NSLog(@"one number is 0");
    }

    NSLog(@"The progress count is = %d", self.progressCount);
}

我遇到的问题是 taskTotalCount 和 taskCompletedCount 设置正确,并在前两个方法中返回不同的数字,而 NSLog 为 x 和 y 返回 0。因此,我不确定在设置两个属性之前是否以某种方式加载了第三种方法,或者是其他一些问题。提前感谢您的任何指点。

4

1 回答 1

1

假设您像这样调用这三个方法:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self CountAndSetCompletedCount];
    [self CountAndSetTotalTask];
    [self CalculateProgress];
}

那么问题是前两个方法立即返回,而对 Parse 的调用发生在后台。这意味着CalculateProgress在您从 Parse 的调用中取回结果之前很久就会调用它。

一种解决方案是CountAndSetCompletedCountviewDidLoad. 然后在其完成处理程序中调用CountAndSetTotalTask. 在其完成处理程序中,您最终调用CalculateProgress.

于 2013-05-18T01:44:45.157 回答