Objective-c 由于数组结构中的数组,replaceObjectAtIndex 不工作
Objective-c replaceObjectAtIndex not working because of array in array structure
我有一个数组,我通过以下代码获得价值:
NSString *status = [[Sweetresponse objectAtIndex:path.row] objectAtIndex:9];
我想更改此值:
[[Sweetresponse objectAtIndex:path.row] replaceObjectAtIndex:9 withObject:@"liked"];
但是它不起作用,因为这个结构是数组中的数组。我该如何解决这个问题?
这是因为 NSArray
是不可变的。你必须让它可变。
NSMutableArray *mutableResponse = [Sweetresponse mutableCopy];
NSMutableArray *mutableResponseItems = [[mutableResponse objectAtIndex:path.row] mutableCopy];
// replace at the index
[mutableResponseItems replaceObjectAtIndex:9 withObject:@"liked"];
// create immutables and replace it with our new array
mutableResponse[path.row] = [mutableResponseItems copy];
// set `Sweetresponse` (assuming it is an NSArray)
Sweetresponse = [mutableResponse copy];
编辑:我不知道 Sweetresponse
到底是什么,这里我假设它是 NSArray
@trojanfoe 认为将此响应解析为自定义对象会导致更清晰的代码和更简单的对象修改。
我有一个数组,我通过以下代码获得价值:
NSString *status = [[Sweetresponse objectAtIndex:path.row] objectAtIndex:9];
我想更改此值:
[[Sweetresponse objectAtIndex:path.row] replaceObjectAtIndex:9 withObject:@"liked"];
但是它不起作用,因为这个结构是数组中的数组。我该如何解决这个问题?
这是因为 NSArray
是不可变的。你必须让它可变。
NSMutableArray *mutableResponse = [Sweetresponse mutableCopy];
NSMutableArray *mutableResponseItems = [[mutableResponse objectAtIndex:path.row] mutableCopy];
// replace at the index
[mutableResponseItems replaceObjectAtIndex:9 withObject:@"liked"];
// create immutables and replace it with our new array
mutableResponse[path.row] = [mutableResponseItems copy];
// set `Sweetresponse` (assuming it is an NSArray)
Sweetresponse = [mutableResponse copy];
编辑:我不知道 Sweetresponse
到底是什么,这里我假设它是 NSArray
@trojanfoe 认为将此响应解析为自定义对象会导致更清晰的代码和更简单的对象修改。