是否可以使用
nil
将属性设置为 NSBatchUpdateRequest
?将 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
。)。
当前 API 允许将
nil
作为常量值传递。
unlockRequest.propertiesToUpdate = ["lockDate": NSExpression(forConstantValue: nil)]
这似乎在 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];
老问题,但这是你在 Swift 中执行此操作的方法,我自己验证过,没有任何崩溃。
// Or Optional<Date>.none as Any
unlockRequest.propertiesToUpdate = ["lockDate": Date?.none as Any]