【问题标题】:How to check NSString type DB object is null?如何检查 NSString 类型的 DB 对象是否为空?
【发布时间】:2016-08-01 13:56:19
【问题描述】:

我只想获取那些没有 null lastname 的 NSString 类型的用户。

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 由于某种原因无法正常工作。应用它后,即使 DB 包含一些姓氏的非 Null 字符串值,也不会返回任何对象。请告诉代码有什么问题,或者有什么方法可以只从核心数据中获取非空字符串。

【问题讨论】:

  • 将单词nil直接放在格式字符串中。
  • 无,无,Null 没用!
  • @Divjyot - 尝试重复的答案一次,如果重复的答案不能解决你的问题,我会再次打开你的问题
  • 将尝试 NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=nil AND name!=' ' "];
  • @Anbu.Karthik 不,原来的答案已经提到它不适用于核心数据.....

标签: ios objective-c core-data iphonecoredatarecipes


【解决方案1】:

您可以使用here描述的方法。

只需替换

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

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

更新

这个谓词将返回 nil 对象

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

此谓词将返回空字符串

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

【讨论】:

  • .length 属性在核心数据中不可用,如果字符串为空,则会失败(因为 0 == 0)。同样,如果 name 为 nil,它也会失败,因为 [nil length] == 0。如stackoverflow.com/questions/7369390/… 中所写
  • 那么,当用户的姓氏为空字符串时,如果用户的姓氏为'nil',情况会有所不同,对吧?
  • nil 可以将自己显示为空姓氏,但空字符串 @" " 不等于 nil。
  • @Divjyot,我知道 :) 但这取决于您的逻辑。两种情况的逻辑是否相同......
猜你喜欢
  • 2017-10-28
  • 2011-09-26
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多