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

ru9i0ody  于 12个月前  发布在  Swift
关注(0)|答案(3)|浏览(117)

是否可以使用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)。

ruyhziif

ruyhziif1#

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

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

fwzugrvs2#

这在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];
dz6r00yl

dz6r00yl3#

老问题,但这里是你在Swift中这样做的方式,在没有任何崩溃的情况下验证自己。

// Or Optional<Date>.none as Any
unlockRequest.propertiesToUpdate = ["lockDate": Date?.none as Any]

相关问题