检查项是否存在,然后在NSMutableArray中替换它

时间:2013-10-17 20:31:44

标签: ios objective-c nsmutablearray

我如何检查一个项目是否存在以及它是否确实在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" ]

2 个答案:

答案 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);
}

一般准则 -

  1. 在构建时注意编译器警告。
  2. 放置断点并逐步执行不起作用的代码。