如何在nsmutablearray中的特定索引处替换对象,该索引在每个索引处包含多个值

时间:2012-04-18 06:45:14

标签: iphone nsmutablearray

我的数组在每个索引处包含(firstName,lastName,age)。现在我想改变一个人在索引1的年龄。请指导如何做到这一点。这是我的代码。

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

}

6 个答案:

答案 0 :(得分:5)

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

假设Person是您的自定义对象存储在数组

答案 1 :(得分:4)

使用此

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

答案 2 :(得分:4)

您应该使用NSMutableDictionary保存姓名,年龄,电话,地址并将此词典添加到您的阵列。

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

像这样你可以改变价值。

答案 3 :(得分:2)

试试这个

   -insertObject:atIndex: or replaceObjectAtIndex:withObject:

答案 4 :(得分:2)

也许这会对你有帮助。

- (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";
    }
}

答案 5 :(得分:1)

假设您的NSMutableArrayNSMutableDictionary个对象组成,

尝试这样的事情:

NSMutableDictionary* entry = [entries objectAtIndex:index];

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