gpt4 book ai didi

iOS 在加载时设置和获取属性

转载 作者:行者123 更新时间:2023-11-29 03:55:00 24 4
gpt4 key购买 nike

我正在尝试在加载 View 时初始化从 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 的调用发生在后台。这意味着 CalculateProgress 早在您从 Parse 调用返回结果之前就被调用了。

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

关于iOS 在加载时设置和获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16619908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com