Search code examples
objective-cnsmutablearraynspredicatefor-in-loop

Search for object in NSMutableArray and change value for that object


I have project where user can add some Items to TableView. My data source for this TableView are objects with 2 properties NSString * nameOfItem and NSNumber * numberOfItem. Is any possibility to check my NSMutableArray if it contain string @"someString" as property nameOfItem and if yes than change numberOfItem +1 ?

UPDATE:

I try to do it with for(...in...) but it works just when i have only one object in my NSMutableArray. If i have more objects there it create one new object and than change value to ++ on old one:

enter image description here

Here is some code what i tried:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString*nameToCheck = [NSString stringWithFormat:@"%@", [self.ivc.objects objectAtIndex:indexPath.row]];
for (Items *itemNamed in self.ivc.shoppingList.items) {
     if ([itemNamed.nameOfItem isEqualToString:nameToCheck]) {
         [itemNamed setNumberOfItem:[NSNumber numberWithInt:[itemNamed.numberOfItem integerValue]+1.0]];
} else {
                Items *item = [Items new];
                [item setNameOfItem:name];
                [item setNumberOfItem:@(1)];
                [self.ivc.shoppingList.items insertObject:item atIndex:0];
}

I want to create new one only if is not yet in that list. Any help appreciated.


Solution

  • I don't know something like this but you can use a NSDictionary instead of NSArray using the name property as a key. And if you don't want to do that, you can sort the array and make a binary search for element.