簡體   English   中英

iOS設置並在加載時獲取屬性

[英]IOS set and get property on load

我正在嘗試初始化加載視圖時從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。 因此,我不確定在設置兩個屬性之前是否以某種方式加載了第三個方法,還是其他一些問題。 預先感謝您提供任何指導。

假設您按以下方式調用這三種方法:

- (void)viewDidLoad {
    [super viewDidLoad];

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

那么問題在於,前兩個方法會在后台調用Parse時立即返回。 這意味着在您從對Parse的調用中獲取結果之前很久就調用了CalculateProgress

一種解決方案是CountAndSetCompletedCount viewDidLoad調用CountAndSetCompletedCount 然后,在其完成處理程序中,調用CountAndSetTotalTask 最后,在其完成處理程序中調用CalculateProgress

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM