简体   繁体   中英

how to replace object at particular index in nsmutablearray which contains multiple value at each index

My array contain (firstName,lastName, age) at each index. now I want to change age of a person at index 1. please guide how to do it. Here is my code.

  - (void)viewDidLoad {
[super viewDidLoad];
productArray=[[NSMutableArray alloc]init];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Adeem";
personObj.lastName = @"Basraa";
personObj.age = @"5";

[productArray addObject:personObj];
[personObj release];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Ijaz";
personObj.lastName = @"Ahmed";
personObj.age = @"10";

[productArray addObject:personObj];
[personObj release];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Waqas";
personObj.lastName = @"Ahmad";
personObj.age = @"15";
[productArray addObject:personObj];
[personObj release];

}

Person *person = (Person *)[myArray objectAtIndex:1];
person.age = 2;

Assuming Person is your custom object stored in the array

用这个

 [arrname replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:13]];//13 is the age you want to change 

You should use NSMutableDictionary to save name,age,phone,address and add this dictionary to your array.

[[arry objectAtIndex:1] setObject:@"value" forKey:@"key"];

Like this you can change value.

尝试这个

   -insertObject:atIndex: or replaceObjectAtIndex:withObject:

Perhaps this will help you.

- (void)viewDidLoad {
[super viewDidLoad];
productArray=[[NSMutableArray alloc]init];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Adeem";
personObj.lastName = @"Basraa";
personObj.phoneNumber = @"123456789";

[productArray addObject:personObj];
[personObj release];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Ijaz";
personObj.lastName = @"Ahmed";
personObj.phoneNumber = @"987654321";

[productArray addObject:personObj];
[personObj release];

PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Waqas";
personObj.lastName = @"Ahmad";
personObj.phoneNumber = @"45656789";
[productArray addObject:personObj];
[personObj release];
}

- (void)change {

for (int i=0;i<[productArray count];i++) {
          PersonDetail *personObj = (PersonDetail *)[[productArray objectAtIndex:i] retain];
          personObj.phoneNumber = @"New";
    }
}

Supposing your NSMutableArray consists of NSMutableDictionary objects,

try something like this :

NSMutableDictionary* entry = [entries objectAtIndex:index];

[entry setValue:@"newAge" forKey:@"Age"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM