Edit and delete elements from an NSMutable array

66 views Asked by At

I have a NSMutableArray whose data is in a dictionary format e.g.:

(
        {
        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;
    },
)

Now I need to combine the roll numbers who belongs to same subject and division and modify the existing array like below

(
        {
        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]; 

But I'm getting error at replace object, so do I have to convert it into NSMutableDictionary? How should I proceed about this to do this in a simple way?

1

There are 1 answers

4
tuledev On BEST ANSWER

Don't need to create more array. You got error because this line:

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

It should be

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

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