我有一个包含12个部分的数组,我需要替换索引处的值。 我的测试代码:
textarea
第一个NSLog返回:NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:@{@"first": @[@"test1", @"test2"]}, @{@"second": @[@"test1"]}, nil];
NSLog(@"%@", [hm valueForKey:@"first"][0][0] );
[[hm valueForKey:@"first"][0] replaceObjectAtIndex:0 withObject:@"lol"];
NSLog(@"%@", hm);
- 确定
替换test1
我需要将test1更改为某些内容。
请问我做错了吗?
答案 0 :(得分:0)
NSMutableArray *arr = [[NSMutableArray alloc] initwithArray[[hm objectAtIndex:0]objectForKey:@"first"]];
[arr replaceObjectAtIndex:0 withObject:@"lol"];
[hm replaceObjectAtIndex:0 withObject:arr];
答案 1 :(得分:0)
NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:@{@"first": @[@"test1", @"test2"]}, @{@"second": @[@"test1"]}, nil];
NSLog(@"%@", [hm valueForKey:@"first"][0][0] );
//Your inner array is immutable, change it to mutable and replace the object, That's it.
NSMutableArray *array = [[hm valueForKey:@"first"][0] mutableCopy];
[array replaceObjectAtIndex:0 withObject:@"lol"];
[hm replaceObjectAtIndex:0 withObject:array];
NSLog(@"%@", hm);
答案 2 :(得分:0)
你必须制作可变的字典和数组结构
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
NSLog(@"Before - %@",names);
[names replaceObjectAtIndex:0 withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Joe_New",@"firstname",
@"Bloggs_New",@"surname",
nil]];
NSLog(@"After - %@",names);
之前 - ( 的 { firstname = Joe; surname = Bloggs; } 下, { firstname =西蒙; 姓氏=圣堂武士; }, { firstname = Amelia; 姓=池塘; } )
之后 - ( 的 { firstname =“Joe_New”; surname =“Bloggs_New”; } 下, { firstname =西蒙; 姓氏=圣堂武士; }, { firstname = Amelia; 姓=池塘; } )
答案 3 :(得分:0)
NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:@{@"first": @[@"test1", @"test2"]}, @{@"second": @[@"test1"]}, nil];
NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[hm objectAtIndex:0]];
NSMutableArray *array=[NSMutableArray arrayWithArray:[dic objectForKey:@"first"]];
[array replaceObjectAtIndex:0 withObject:@"lol"];
[dic setObject:array forKey:@"first"];
[hm replaceObjectAtIndex:0 withObject:array];
O/P (ViewController.m:48) (
(
lol,
test2
),
{
second = (
test1
);
}
)