1

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?

2
  • Are you getting index of object ? Commented Nov 18, 2013 at 11:38
  • yes, I have index of object as 1 (in my case) Commented Nov 18, 2013 at 11:39

5 Answers 5

4
NSMutableDictionary *miladData = [array[1] mutableCopy];
[miladData setObject:@"New Name" forKey:@"Name"];
[array replaceObjectAtIndex:1 withObject:miladData];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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.

Comments

1

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

[arrayOfData replaceObjectAtIndex:yourIndex withObject:yourObject];

2 Comments

what will be yourObject?
That will be object of your dict having Id,Name
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.