我如何检查一个项目是否存在以及它是否确实在NSMutableArray中替换它我只是无法弄清楚到目前为止我所拥有的是:
int i = [arrayOne indexOfObject:@"object to replace"];
NSLog(@"%@", i);
[arrayOne replaceObjectAtIndex:i withObject:@"replace"];
但我不断收到错误:S可以帮助我吗?
我的数组是:
@[ "13L6-A67-1", "13NAPUSD-A1", "13NASUWO-X1", "13NASUWO-X1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1" ]
答案 0 :(得分:1)
如果数组中没有对象,则返回NSNotFound值,因此您需要检查它:
if (i != NSNotFound)
[arrayOne replaceObjectAtIndex:i withObject:@"replace"];
另请注意,如果要打印整数值,则应使用%d
格式说明符,%@
用于objective-c对象
答案 1 :(得分:0)
看来你是这个平台的新手。所以这是有效的示例代码 -
NSMutableArray *arrayOne = [@[@"13L6-A67-1",@"13NAPUSD-A1",@"13NASUWO-X1",@"13NASUWO-X1",@"13ASECON-D1",@"13ASECON-D1",@"13ASECON-D1",@"13ASECON-D1",@"13ASMATH-C1",@"13ASMATH-C1",@"13ASMATH-C1",@"13ASMATH-C1",@"13ASPHYS-B1",@"13ASPHYS-B1",@"13ASPHYS-B1",@"13ASPHYS-B1",@"13B3ITCE-F1",@"13B3ITCE-F1",@"13B3ITCE-F1",@"13B3ITCE-F1" ] mutableCopy];
NSUInteger index = [arrayOne indexOfObject:@"13ASECON-D1"];
if (index != NSNotFound) {
[arrayOne replaceObjectAtIndex:index withObject:@"DIFFERENT_VALUE"];
NSLog(@"arrayOne after replaceObjectAtIndex = %@", arrayOne);
}
一般准则 -