这是我的代码:
NSMutableArray *ratings = [[NSMutableArray alloc] init];
NSMutableDictionary *eachRating = [[NSMutableDictionary alloc] init];
for (UIView *subview in self.rateServiceView.subviews) {
if ([subview isKindOfClass:[RSTapRateView class]]) {
RSTapRateView *rs = (RSTapRateView *)subview;
[eachRating setObject:rs.rateId forKey:@"iRatingId"];
[eachRating setObject:[NSNumber numberWithInt:rs.rating] forKey:@"iRate"];
[ratings addObject:eachRating];
}
}
而不是获取这些值:
{
iRate = 1;
iRatingId = 1;
},
{
iRate = 5;
iRatingId = 2;
},
{
iRate = 2;
iRatingId = 3;
}
我得到了这些价值观:
{
iRate = 2;
iRatingId = 3;
},
{
iRate = 2;
iRatingId = 3;
},
{
iRate = 2;
iRatingId = 3;
}
当我记录每次迭代的结果时,最后一个对象替换所有现有对象并为自己添加一个新对象。
答案 0 :(得分:2)
移动这一行:
NSMutableDictionary *eachRating = [[NSMutableDictionary alloc] init];
下面的 这一行:
for (UIView *subview in self.rateServiceView.subviews) {
这样,您就可以创建一个新的“eachRating
”字典,并将其添加到“ratings
”数组中。
答案 1 :(得分:1)
是的,这是因为您要为同一个键分配不同的值,因此新值将替换该键的旧值。
因此请将代码更改为:
NSMutableArray *ratings = [[NSMutableArray alloc] init];
for (UIView *subview in self.rateServiceView.subviews){
if ([subview isKindOfClass:[RSTapRateView class]]) {
NSMutableDictionary *eachRating = [[NSMutableDictionary alloc] init];
RSTapRateView *rs = (RSTapRateView *)subview;
[eachRating setObject:rs.rateId forKey:@"iRatingId"];
[eachRating setObject:[NSNumber numberWithInt:rs.rating] forKey:@"iRate"];
[ratings addObject:eachRating];
}
}
答案 2 :(得分:0)
如果你不需要在这个循环之后进一步改变单个词典,你可以通过这样编写来获得更加现代和紧凑:
NSMutableArray *ratings = [[NSMutableArray alloc] init];
for (UIView *subview in self.rateServiceView.subviews) {
if ([subview isKindOfClass:[RSTapRateView class]]) {
RSTapRateView *rs = (RSTapRateView *)subview;
[ratings addObject:@{@"iRatingId":rs.rateId, @"iRate":@(rs.rating)}];
}
}