3

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 .

djay
  • 375
  • 2
  • 18

1 Answers1

0

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 = ''"];
Community
  • 1
  • 1
Che
  • 984
  • 8
  • 12
  • .length property is not available in core data and If the string is empty, this will fail (because 0 == 0). Similarly, if name is nil, it will also fail, because [nil length] == 0. as wriiten in http://stackoverflow.com/questions/7369390/nspredicate-to-test-for-null-and-blank-strings – djay Apr 11 '16 at 12:25
  • So, when user has empty string as 'lastname' will be different case if user has 'nil' as lastname, right? – Che Apr 11 '16 at 12:53
  • nil can show itself as empty lastname but an empty string @" " is not equal to nil. – djay Apr 11 '16 at 13:07
  • @Divjyot, I know :) But it depend from your logic. Is logic the same for both cases or not… – Che Apr 11 '16 at 13:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108824/discussion-between-divjyot-and-che). – djay Apr 11 '16 at 13:50