How to check NSString type DB object is null?

124 Views Asked by At

I wanted to fetch only those users who do not have null lastname which of NSString type.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER" inManagedObjectContext:dbHandler.managedObjectContext];

    NSMutableArray * predicateArray = [[NSMutableArray alloc] init];

    NSPredicate * predicate1 = [NSPredicate predicateWithFormat:@"id = %@",abc];
    [predicateArray addObject:predicate1];

    NSPredicate * predicate2 = [NSPredicate predicateWithFormat:@"lastname != %@",nil];
    [predicateArray addObject:predicate2];

    NSCompoundPredicate * resultantPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray];

    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:resultantPredicate];

    NSError *fetchError = nil;

    NSArray *result = [dbHandler.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];

Predicate2 is not working for some reason.After applying it no object is returned even if DB contains some Non-Null string values of lastname. Please tell what is wrong in the code or is there any way to fetch not-null string ONLY from core data .

1

There are 1 best solutions below

5
Che On

You can use method which is described here.

Just replace

[NSPredicate predicateWithFormat:@"lastname != %@",nil]

with

[NSPredicate predicateWithFormat:@"lastname.length > 0"]

UPDATE

This predicates will return nil objects

[NSPredicate predicateWithFormat:@"lastname = NULL"];
[NSPredicate predicateWithFormat:@"lastname = NIL"];

This predicate will return empty strings

[NSPredicate predicateWithFormat:@"lastname = ''"];