使用 NSBatchUpdateRequest 将 Core Data 属性设置为 nil

Posted

技术标签:

【中文标题】使用 NSBatchUpdateRequest 将 Core Data 属性设置为 nil【英文标题】:Setting Core Data attribute to nil with NSBatchUpdateRequest 【发布时间】:2015-09-03 18:37:42 【问题描述】:

是否可以使用NSBatchUpdateRequest 将属性设置为nil?将NSNull() 传递给propertiesToUpdate 不起作用:

let unlockRequest = NSBatchUpdateRequest(entityName: "MyEntity")
unlockRequest.predicate = NSPredicate(format: "self in %@", myObjectIDs)
unlockRequest.propertiesToUpdate = ["lockDate": NSNull()]
var error: NSError?
myContext.executeRequest(unlockRequest, error: &error)
if let error = error 
    log.error("Failed to unlock: \(error)")

我没有收到任何错误,但它没有清除日期。

我也尝试将其设置为NSExpression(forConstantValue: NSNull()),但这也不起作用(forConstantValue 参数不接受可选值,所以我无法传递它nil。)。

【问题讨论】:

你试过 NSExpression(constantValue: nil) 吗? @Willeke 遗憾的是它不接受可选值,所以我不能将它传递为零。 @Sencha 你找到解决方案了吗? @Serluca 不,我从来没有这样做过,最后我不得不将我的锁定日期设置为过去的日期,以有效地使锁定无效(我可以接受,但我确定在其他情况下不会) . 【参考方案1】:

当前 API 允许将 nil 作为常量值传递。

unlockRequest.propertiesToUpdate = ["lockDate": NSExpression(forConstantValue: nil)]

【讨论】:

我可以看到方法签名现在接受 Swift 选项。如果这被验证可以工作,那么问题就解决了! NSExpression.init(forConstantValue obj: Any?) 编译器没有报错,但是当我执行请求时它会抛出异常:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid string key (null) passed to propertiesToUpdate:' NSBatchUpdateRequest.propertiesToUpdate 的标头说:“表达式可以是任何NSExpression,其计算结果为标量值。”【参考方案2】:

这似乎在 Objective-C 中可以正常工作:

NSBatchUpdateRequest *batch = [[NSBatchUpdateRequest alloc] initWithEntityName:entityName];
NSExpression *value = [NSExpression expressionForConstantValue: nil];
batch.propertiesToUpdate = @@"lockDate": value;
batch.resultType = NSUpdatedObjectsCountResultType;
NSError *error;                
NSBatchUpdateResult *results = [self.privateContext executeRequest:batch error:&error];

【讨论】:

以上是关于使用 NSBatchUpdateRequest 将 Core Data 属性设置为 nil的主要内容,如果未能解决你的问题,请参考以下文章

NSFetchedResultsController 不知道数据已被 NSBatchUpdateRequest 更改

NSBatchUpdateRequest 不保存可转换属性

核心数据批量更新

NSManagedObjectContext 的 exeucteRequest:error: 返回 nil

批量更新后更新托管对象上下文中的托管对象

我可以将 Visual C++ 用于将使用 gcc 编译的作业吗?