IOS在加载时设置并获取属性

时间:2013-05-18 01:36:46

标签: ios objective-c parse-platform

我正在尝试在加载视图时初始化从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。因此,我不确定第三种方法是否在设置两个属性之前以某种方式加载,或者是其他一些问题。提前感谢您的任何指示。

1 个答案:

答案 0 :(得分:1)

假设您将这三种方法称为:

- (void)viewDidLoad {
    [super viewDidLoad];

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

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

一种解决方案是从CountAndSetCompletedCount拨打viewDidLoad。在完成处理程序中,然后调用CountAndSetTotalTask。在完成处理程序中,您最后调用CalculateProgress