lagos
lagos

Reputation: 1968

NSPredicate check NSArray if object has one of several ID

Little diifficult to explain but I am trying to use NSPredicate for filtering an array with custom NSManagedObject by ids. I have a server that can send update, delete or add new objects, and I need to control if those objects from the JSON file already exist, if exist just update them or insert to core 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 unlike some storeId, and next id will match.

Json file is some sort of this :

     "Stores":[{
          "id":1,
          "name":"Spar",
          "city":"London"
          }
          {
           "id":2,
           "name":"WalMart",
           "city":"Chicago"
       }];

Upvotes: 7

Views: 3867

Answers (2)

Martin R
Martin R

Reputation: 539965

I am not sure if I understand correctly what you are trying to achieve, but perhaps 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 that have a storeId that is not equal to any of the ids in the jsonFile array.

Upvotes: 12

David Hoerl
David Hoerl

Reputation: 41642

The syntax of the predicate is probably off - someone else may suggest a fix - but if you have an array, why not use

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

since its much easier:

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

Upvotes: 0

Related Questions