Fahim Parkar
Fahim Parkar

Reputation: 31647

update NSMutableArray based on index

I have NSMutableArray as below.

I have NSMutableArray data as below.

(
        {
        Id = 3;
        Name = Fahim;
    },
        {
        Id = 2;
        Name = milad;
    },
        {
        Id = 1;
        Name = Test;
    }
)

I want to change milad to New Name

Means I want to update the data of object at index 1.

Any idea how to get this done?

Upvotes: 1

Views: 454

Answers (5)

Ian
Ian

Reputation: 3709

If the objects in the array are mutable (an NSMutableDictionary, say), you can change the actual field, and you don't have to replace anything in the array:

NSMutableDictionary *dict = [array objectAtIndex:1];
[dict setObject:@"New Name" forKey:@"Name"];

If the objects in the array are immutable, you'll have to replace the object at the correct index:

NSDictionary *dict = @{@"Id":@2, @"Name":@"New Name"};
[array replaceObejectAtIndex:1 withObject:dict];

You can also do this by creating a mutable copy (but in this case, unlike the first, you have to set it back into the array):

NSMutableDictionary *dict = [[array objectAtIndex:1] mutableCopy];
[dict setObject:@"New Name" forKey:@"Name"];
[array replaceObejectAtIndex:1 withObject:dict];

The Id values in your dictionaries, incidentally, are not what we're using to locate things in your array. As you specified, we're using indexes. If you want to look up values based on those Id records, say so, because the code will be different then.

Upvotes: 2

Amar
Amar

Reputation: 13222

You need to create a mutable copy of the dictionary object at given index in your NSMutableArray. Modify the value for required key. Use the NSMutableArray API

[mutableArray replaceObjectAtIndex:index withObject:mutableCopiedObj];

Hope that helps!

Upvotes: 1

SandeepM
SandeepM

Reputation: 2609

NSMutableDictionary *tempDict = [[yourArray objectAtIndex:1] mutableCopy];
[tempDict setObject:@"New Name" forKey:@"Name"];
[yourArray replaceObjectAtIndex:1 withObject:tempDict];

Upvotes: 2

in.disee
in.disee

Reputation: 1112

NSMutableDictionary *miladData = [array[1] mutableCopy];
[miladData setObject:@"New Name" forKey:@"Name"];
[array replaceObjectAtIndex:1 withObject:miladData];

Upvotes: 4

βhargavḯ
βhargavḯ

Reputation: 9836

You should replace your object once you get index of object.

[arrayOfData replaceObjectAtIndex:yourIndex withObject:yourObject];

Upvotes: 1

Related Questions