0

这是我的代码:

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;
    }

当我记录每次迭代的结果时,最后一个对象会替换所有现有对象并为自己添加一个新对象。

4

3 回答 3

2

移动这一行:

    NSMutableDictionary *eachRating = [[NSMutableDictionary alloc] init];

一直到这条线以下

    for (UIView *subview in self.rateServiceView.subviews) {

这样,您将创建一个新的 " eachRating" 字典,并将其添加到 " ratings" 数组中。

于 2013-08-19T08:34:03.800 回答
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];

        }

    }
于 2013-08-19T08:33:51.500 回答
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)}];

    }

}
于 2013-08-19T08:40:43.437 回答