This question already has an answer here:
- Search NSArray for value matching value 8 answers
So here I grab all my objects from core data and store in an NSArray:
// Set up fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"BagItem"];
// Get fetched objects and store in NSArray
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
Each object has a title property, a size property and a colour property. I have a UIPickerView and from here I can select sizes and colours for a specific item then tap apply to store them using core data.
I'd like to prevent duplicate rows. For example:
Leather Coat, Blue, X-Large (Quantity 5)
Leather Coat, Blue, X-Large (Quantity 1)
I want to avoid this and instead detect that an object with a specific title, size and colour already exists. If it does I'd like to update the quantity label of the existing row.
So far I have half done this. I have a detail view controller that detects this and does the magic before I switch over to a tableView that displays the objects. However while on the tableView I allow customers to edit the colour and size. This gives customers the opportunity to update the object/item's properties to any colour and size they wish even if there is an existing identical item with the same colour and size set.
I am trying to prevent this. What I want to do is:
Search array for item with matching title, size and colour of the current item I am trying to modify.
Update the quantity label of the matching item.
Then remove the row of the item no longer needed.*
I just thought it would be best to explain what I was trying to do.
So what I need to know is how to search my NSArray for an item whose NSString properties match another set of NSStrings.
Thanks for your time.
You can use a NSPredicate:
You can get the sum with KVC, something like:
You could then create a new BagItem instance with the same values for title colour and size and the new quantity value. Than it's up to you to update your model and reload your table as per your setup.