这是我的密码:
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;
}当我记录每次迭代的结果时,最后一个对象将替换所有现有的对象,并为自己添加一个新的对象。
发布于 2013-08-19 08:34:03
移动这一行:
NSMutableDictionary *eachRating = [[NSMutableDictionary alloc] init];下面是,在下面,这一行:
for (UIView *subview in self.rateServiceView.subviews) {这样,您将创建一个新的"eachRating“字典,并将其添加到"ratings”数组中。
发布于 2013-08-19 08:33:51
是的,这是因为您为同一键分配了不同的值,因此新值取代了该键的旧值。
因此,将代码更改为:
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];
}
}发布于 2013-08-19 08:40:43
如果您不需要在这个循环之后进一步修改单个字典,您可以这样编写它,使其更加现代化和紧凑:
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)}];
}
}https://stackoverflow.com/questions/18309486
复制相似问题