Check NSPredicate NSArray if an object has one of several identifiers

It's a little hard to explain, but I'm trying to use NSPredicate to filter an array using a custom NSManagedObject using identifiers. I have a server that can send updates, delete or add new objects, and I need to manage if these objects from the JSON file already exist, if they simply update them or insert them into the main data, if not.

I am using this predicate now:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"storeId != %@", [jsonFile valueForKey:@"Id"]; 

Where jsonFile contains Unparsed Store objects. But with this predicate, it will give me a huge array, since one id will be different from some storeId, and the next id will match.

The json file is something like this:

  "Stores":[{ "id":1, "name":"Spar", "city":"London" } { "id":2, "name":"WalMart", "city":"Chicago" }]; 
+6
source share
2 answers

I'm not sure if I understand correctly what you are trying to achieve, but maybe you can use the following:

 NSArray *jsonFile = /* your array of dictionaries */; NSArray *idList = [jsonFile valueForKey:@"id"]; // array of "id" numbers NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(storeId IN %@)", idList]; 

This will give all managed objects with storeId that are not equal to any of the identifiers in the jsonFile array.

+11
source

The predicate syntax is probably turned off - someone might suggest a fix, but if you have an array, why not use

 - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate 

since it is much simpler:

 NSInteger textID = ... // you set this NSInteger idx = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)) { NSInteger objIdx = [obj objectForKey:@"id"] integerValue]; // integerValue works for both NSNUmbers and NSStrings if(objIdx == testID) { return YES; *stop = YES; } } 
0
source

Source: https://habr.com/ru/post/921671/


All Articles