Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate query for not containing a specific string

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];
like image 684
sangony Avatar asked Sep 21 '12 16:09

sangony


1 Answers

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];
like image 82
Martin R Avatar answered Nov 07 '22 10:11

Martin R