编辑和删除NSMutable数组中的元素

时间:2015-11-02 10:15:11

标签: ios objective-c nsmutablearray nsmutabledictionary ios7.1

我有一个NSMutableArray,其数据是字典格式,例如:

(
        {
        subject = “Maths";
        rollNo = "#1";
        division = A;
    },
        {
        subject = “Science”;
        rollNo = “#2”;
        division = A;
    },
 {
        subject = “Maths";
        rollNo = “#3”;
        division = A;
    },
 {
        subject = “Maths";
        rollNo = “#4”;
        division = B;
    },
 {
        subject = “Science”;
        rollNo = “#5”;
        division = A;
    },
 {
        subject = “English”;
        rollNo = “#6”;
        division = A;
    },
)

现在我需要组合属于同一主题和分区的滚动编号,并修改现有数组,如下所示

(
        {
        subject = “Maths";
        rollNo = “#1,#3”;
        division = A;
    },
        {
        subject = “Science”;
        rollNo = “#2,#5”;
        division = A;
    },

 {
        subject = “Maths";
        rollNo = “#4”;
        division = B;
    },

 {
        subject = “English”;
        rollNo = “#6”;
        division = A;
    },
)

This is how I'm trying to achieve it

 NSMutableArray *temp =[studentDetailsArray mutableCopy];
 NSMutableArray *elementToDelete = [NSMutableArray array];
 for (int m=0; m<temp.count-1; m++)
 {
 if ([temp[m][@"subject"] isEqualToString:temp[m+1][@"subject"]] && [temp[m][@“division”] isEqualToString:temp[m+1][@“division”]])
 {
 [temp[m] replaceObjectAtIndex:1 withObject:@{@"rollNo":[NSString stringWithFormat:@"%@, %@",temp[m][@"rollNo"],temp[m+1][@"rollNo"]]}];
 //                    [temp[m] setValue:[NSString stringWithFormat:@"%@, %@",temp[m][@"rollNo"],temp[m+1][@"rollNo"]]forKey:@"rollNo"];
 [elementToDelete addObject:temp[m+1]];
 }
 }

 [temp removeObjectsInArray:elementToDelete]; 

但我在替换对象时遇到错误,所以我必须将其转换为NSMutableDictionary吗?我应该如何以简单的方式解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

不需要创建更多数组。 你有错误,因为这一行:

[temp[m] replaceObjectAtIndex:1 withObject:@{@"rollNo":[NSString stringWithFormat:@"%@, %@",temp[m][@"rollNo"],temp[m+1][@"rollNo"]]}];

应该是

NSMutableDictionary *mutable = [temp[m] mutableCopy];

[mutable setObject:[NSString stringWithFormat:@"%@, %@",temp[m][@"rollNo"],temp[m+1][@"rollNo"]] forKey:@"rollNo"];
[temp replaceObjectAtIndex:m withObject:mutable];