从NSMutableArray中删除对象?

Nav*_*een 5 search objective-c nsstring nsmutablearray ios

我在ViewDidLoad方法中有一个包含以下元素的数组

inputArray = [NSMutableArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];
Run Code Online (Sandbox Code Playgroud)

我还有一个UITextField用于搜索的元素.所以一旦我输入一些东西UITextField,我想检查该字符串是否存在"inputArray"或not.If它不与inputArray元素匹配然后从inputArray相应的元素.

 for (NSString* item in inputArray)
   {
        if ([item rangeOfString:s].location == NSNotFound) 
        {
            [inputArray removeObjectIdenticalTo:item];//--> Shows Exception
            NSLog(@"Contains :%@",containsAnother);
        }

  }
Run Code Online (Sandbox Code Playgroud)

但此代码显示异常,与"removeobject:"相关的内容

例外:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString rangeOfString:options:range:locale:]: nil argument'
*** First throw call stack:
`
Run Code Online (Sandbox Code Playgroud)

Ano*_*dya 10

In fast enumeration you can NOT modify the collection.

The enumerator object becomes constant and immutable.

If you want to do updation on the array

You should like this :

NSMutableArray *inputArray = [NSMutableArray arrayWithObjects:@"car", @"bus", @"helicopter", @"cruiz", @"bike", @"jeep", nil];
NSString *s=@"bus";

for (int i=inputArray.count-1; i>-1; i--) {
    NSString *item = [inputArray objectAtIndex:i];
    if ([item rangeOfString:s].location == NSNotFound) {
        [inputArray removeObject:item];
    }
}
Run Code Online (Sandbox Code Playgroud)

EDIT:

The above works similar as this :

NSArray *array=[inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",s]]; 
Run Code Online (Sandbox Code Playgroud)

  • @Rob我喜欢直接使用`filterUsingPredicate:`的想法 - 它在一个易于理解的代码行中完成了OP所要求的. (3认同)

Muh*_*rif 10

您可以使用以下代码

for (int i=0;i<[inputArray count]; i++) {
        NSString *item = [inputArray objectAtIndex:i];
        if ([item rangeOfString:s].location == NSNotFound) {
            [inputArray removeObject:item];
            i--;
        }
    }
Run Code Online (Sandbox Code Playgroud)