NSPredicate query for not containing a specific string

sangony picture sangony · Sep 21, 2012 · Viewed 34.7k times · Source

Looked high and low for this one but can't find my answer. I am looking to query core data for all records which are NOT equal to a specified string. For example, all records which are not equal to the current session ID. I have tried these to no avail:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"listingID != %@", [sitListingID objectAtIndex:i]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ NOT CONTAINS[cd] %@",@"listingID", [sitListingID objectAtIndex:i]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ NOT CONTAINS %@",@"listingID", [sitListingID objectAtIndex:i]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"listingID NOT like %@", [sitListingID objectAtIndex:i]];

Nothing works.HEEEEELP!!! ----------------------------------------------------- more code

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ListingRecord" inManagedObjectContext:context];
    [request setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sessionID <> %@", uniqueSessionListings];
    [request setPredicate:predicate];
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];

Answer

Martin R picture Martin R · Sep 21, 2012

Your first predicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"listingID != %@", sessionID];

should work to find all records where the attribute listingID is not equal to sessionID (provided that listingID and sessionID have the same type).

If both are strings and you want to find all records where listingID does not contain the string sessionID as a substring, then this predicate should work:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (listingID CONTAINS %@)", sessionID];

Use "CONTAINS[cd]" if the string comparison should be done case and diacritical insensitive.

NOTE: You can specify the attribute name as an argument, but then you must use %K instead of %@ as format:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (%K CONTAINS %@)", @"listingID", sessionID];