Search code examples
objective-ccore-datanspredicatemagicalrecord

NSPredicate with "NOT IN" condition fails


Ok, here's my problem. I am synchronizing data from a server via a REST-api. The returned data is in JSON, I loop through it and takes appropriate actions depending on the data. That is, I either store it as a new object, updates the object if it already exists or deletes it if only exists locally.

To achieve this, I collect the IDs from the returned objects when I loop through the JSON. This gives me a index of all the returned objects. I then query my locally stored data to see if it contains any objects that should be deleted (in other words, if the local ID does exists or not in the JSON response).

And here's my issue (sorry for a somewhat lengthy prologue); the NSPredicate that I use only works for certain scenarios and which ones work or fails seems to be random.

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {

    // Array which populates with the IDs from the server
    NSMutableArray *arrayOfLogIDS = [[NSMutableArray alloc] init];

    /*
    Fetching and parsing JSON ... collecting IDs and adding them to the array. See example below;
    */
    NSArray *logs = [[json valueForKey:@"Logs"] valueForKey:@"Object"];

    // Looping through the logs array
    for (NSArray *log in logs) {

        [arrayOfLogIDS addObject:[log valueForKey:@"serverID"]];

    }
    // The NSPredicate
    NSPredicate *serverIDS = [NSPredicate predicateWithFormat:@"NOT (serverID IN %@)", arrayOfLogIDS];

    // The array which holds the objects that should be deleted
    NSArray *logs = [Logs MR_findAllWithPredicate:serverIDS inContext:localContext];

}];

The problem is just that the NSPredicate won't work for this specific circumstance. It returns no results even though I know I have objects locally that should be deleted. I use this approach in other places in the application, and it works as expected. As you can see I am using Magical Record for Core Data management in this app.

I feel that I have completely run out of things to try next, so any help would be much appreciated! :)


Solution

  • Ok, as it turns out, the array of IDs sometimes had the values stored as string and sometimes as integers. Integers worked well with NSPredicate, strings not so much :) Solved! Thanks all for your time.