2013-05-18 74 views
0

我试图初始化一些从parse.com获取的属性,当视图加载时,我可以使用它们进行计算。举例来说,我宣布了以下在我的头文件:iOS设置并获取加载属性

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。因此,我不确定第三种方法在设置两个属性之前是否已加载,或者是其他一些问题。提前感谢您的任何指示。

+0

显示如何调用这三种方法。 – rmaddy

+0

我把它和您在答案中指出的方式一样。 – Poyi

回答

1

假设你调用这三个方法是这样的:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

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

那么问题是,前两种方法的同时立即返回调用解析出现在背景中。这意味着CalculateProgress在调用Parse返回结果之前调用很久。

一个解决方案是从viewDidLoad只需拨打CountAndSetCompletedCount。在完成处理程序中,您可以拨打CountAndSetTotalTask。在完成处理程序中,您最终会调用CalculateProgress

+0

谢谢你的回答,让我给你一个机会,并回复你。 – Poyi

+0

是的,就是这样。在获取结果之前调用CalculatedProgress。我只需要在其他方法完成后调用CalculateProgress方法。再次感谢! – Poyi