【问题标题】:Fetch coredate record where boolean column value is NO or nil获取布尔列值为 NO 或 nil 的 coredate 记录
【发布时间】:2015-06-01 17:31:38
【问题描述】:

我想从我的实体中获取数据,其中特定列 (isDelete) 的值为 nil or NO 。我使用下面的代码:

    NSManagedObjectContext *managedObjectContext = [LIUtility sharedUtility].managedObjectContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NumberStorage" inManagedObjectContext:managedObjectContext];
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    [fetch setEntity:entity];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(type = %d) and isDelete != YES",type];
        [fetch setPredicate:predicate];

 allCardNumber = [managedObjectContext executeFetchRequest:fetch error:nil];

但它不起作用。

我应该如何查询这个请求?

【问题讨论】:

    标签: ios objective-c iphone core-data


    【解决方案1】:

    Predicate Programming Guide,您必须显式测试 nil:

    空值测试
    如果要匹配空值,除了其他比较之外,还必须包含特定测试

    所以,修改你的谓词:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(type = %d) AND (isDelete == NO OR isDelete == nil)",type];
    

    【讨论】:

      【解决方案2】:

      这应该可行,

      NSManagedObjectContext *managedObjectContext = [LIUtility sharedUtility].managedObjectContext;
      NSEntityDescription *entity = [NSEntityDescription entityForName:@"NumberStorage" inManagedObjectContext:managedObjectContext];
      NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
      [fetch setEntity:entity];
      
      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(type = %d) and isDelete != %@",type, @YES];
      [fetch setPredicate:predicate];
      
      allCardNumber = [managedObjectContext executeFetchRequest:fetch error:nil];
      

      如果您在模型编辑器中为布尔属性设置默认值而不是将其设置为 nil,那就太好了。

      【讨论】:

      • 让我再描述一下,在我以前的版本中,我有一个没有“isDelete”列的实体。在新版本中,我创建此列并将默认值设置为 NO。我也做轻量级迁移。现在我安装新版本。我希望当我使用“isDelete=No”查询时,我的先前版本的记录也会被提取。但他们不取。只有当我不查询 isDelete 列时,它们才会获取。现在我也尝试了你的代码,但它也不起作用:(
      猜你喜欢
      • 2015-04-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2016-01-18
      • 2020-04-10
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多