0

我的数组在每个索引处包含 (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];

}

4

6 回答 6

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

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

于 2012-04-18T06:51:28.307 回答
4

用这个

[arrname replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:13]];//13 is the age you want to change
于 2012-04-18T06:51:18.983 回答
4

您应该使用NSMutableDictionary保存姓名、年龄、电话、地址并将此字典添加到您的数组中。

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

像这样你可以改变价值。

于 2012-04-18T06:56:53.540 回答
2

试试这个

   -insertObject:atIndex: or replaceObjectAtIndex:withObject:
于 2012-04-18T06:55:15.593 回答
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";
    }
}
于 2012-04-18T07:03:16.733 回答
1

假设您NSMutableArrayNSMutableDictionary对象组成,

尝试这样的事情:

NSMutableDictionary* entry = [entries objectAtIndex:index];

[entry setValue:@"newAge" forKey:@"Age"];
于 2012-04-18T06:51:16.980 回答