Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from NSMutableArray?

I have an array with following elements in ViewDidLoad method

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

I have another UITextField for searching the elements .So once i type some thing in UITextField i want to check whether that string is present in "inputArray" or not.If it is not matching with elements in inputArray then remove the corresponding elements from inputArray .

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

  }

but this code shows exception , something related to "removeobject:"

Exception :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString rangeOfString:options:range:locale:]: nil argument'
*** First throw call stack:
`
like image 583
Naveen Avatar asked Apr 15 '13 13:04

Naveen


2 Answers

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];
    }
}

EDIT:

The above works similar as this :

NSArray *array=[inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",s]]; 
like image 79
Anoop Vaidya Avatar answered Nov 06 '22 14:11

Anoop Vaidya


You can use the following code

for (int i=0;i<[inputArray count]; i++) {
        NSString *item = [inputArray objectAtIndex:i];
        if ([item rangeOfString:s].location == NSNotFound) {
            [inputArray removeObject:item];
            i--;
        }
    }
like image 39
Muhammad Nabeel Arif Avatar answered Nov 06 '22 12:11

Muhammad Nabeel Arif