我使用的是Parse,并且有一些等级的作业(数量为1/5)。我想查询类并将每个评级粘贴到一个数组中,然后计算平均值。但是,当我尝试将对象添加到数组中时,它似乎只添加了查询返回的最后一项,我无法弄清楚原因。
- (void)viewDidLoad {
[super viewDidLoad];
self.jobName = [self.job objectForKey:@"jobTitle"]; //jobName string
self.title = [NSString stringWithFormat:@"%@", self.jobName];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
PFQuery *getCompletedJobsQuery = [PFQuery queryWithClassName:@"completedJobs"];
[getCompletedJobsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.completedJobs = objects;
for (PFObject *completedJob in objects) {
self.ratingsArray = [[NSMutableArray alloc] init];
NSLog(@"RATING: %@", [completedJob objectForKey:@"customerRating"]);
[self.ratingsArray addObject:[completedJob objectForKey:@"customerRating"]];
}
NSLog(@"ratings array ... %@", self.ratingsArray);
[self.tableView reloadData];
} else {
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
}
当它运行时,它会记录每个评级,但是当我尝试打印出数组或检查其长度时,它只显示最后一个对象而不包含其他对象:
2015-01-05 13:05:00.274 Ribbit[15538:251863] RATING: 3
2015-01-05 13:05:00.274 Ribbit[15538:251863] RATING: 5
2015-01-05 13:05:00.274 Ribbit[15538:251863] RATING: 4
2015-01-05 13:05:00.274 Ribbit[15538:251863] RATING: 5
2015-01-05 13:05:00.275 Ribbit[15538:251863] ratings array ... (
5
)
那么,从Parse检索内容并将它们放入数组的正确方法是什么?
编辑:正如oltman和Jack所指出的,每次循环运行时我都会重新创建数组,因此在循环外部移动数组创建可以解决问题。这也是我的队列,从编码中休息几个小时,坐在我的耻辱立方体。谢谢!
答案 0 :(得分:3)
您每次循环迭代都会创建一个新数组(self.ratingsArray = [[NSMutableArray alloc] init];
)。将此行移出循环(到循环之前),你应该使用不仅仅是数组中的最后一个对象来使用它。
答案 1 :(得分:2)
您正在循环的每次迭代中重新创建数组:
for (PFObject *completedJob in objects) {
self.ratingsArray = [[NSMutableArray alloc] init]; // HERE
NSLog(@"RATING: %@", [completedJob objectForKey:@"customerRating"]);
[self.ratingsArray addObject:[completedJob objectForKey:@"customerRating"]];
}
将其移到循环之外:
self.ratingsArray = [[NSMutableArray alloc] init]; // HERE
for (PFObject *completedJob in objects) {
NSLog(@"RATING: %@", [completedJob objectForKey:@"customerRating"]);
[self.ratingsArray addObject:[completedJob objectForKey:@"customerRating"]];
}