获取布尔列值为 NO 或 nil 的 coredate 记录
Posted
技术标签:
【中文标题】获取布尔列值为 NO 或 nil 的 coredate 记录【英文标题】:Fetch coredate record where boolean column value is NO or nil 【发布时间】: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];
但它不起作用。
我应该如何查询这个请求?
【问题讨论】:
【参考方案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 列时,它们才会获取。现在我也尝试了你的代码,但它也不起作用:(以上是关于获取布尔列值为 NO 或 nil 的 coredate 记录的主要内容,如果未能解决你的问题,请参考以下文章
如何从多个布尔列中检查至少一个为真或所有列值在 SQL Server 中为假