您对完成块中分配给外部ref变量的值的范围有什么困惑。例如,在下面的代码中,operationError和savedRecords的值将在完成块之外保留。
func applyLocalChangesToServer(insertedOrUpdatedCKRecords:Array<CKRecord>,deletedCKRecordIDs:Array<CKRecordID>) throws
{
var savedRecords:[CKRecord]?
var conflictedRecords:[CKRecord] = [CKRecord]()
var removeRecords:[CKRecord] = [CKRecord]()
var operationError : NSError?
let ckModifyRecordsOperation = CKModifyRecordsOperation(recordsToSave:insertedOrUpdatedCKRecords, recordIDsToDelete: deletedCKRecordIDs);
ckModifyRecordsOperation.atomic = true
ckModifyRecordsOperation.modifyRecordsCompletionBlock = ({(savedRecords1,deletedRecordIDs1,error)->Void in
operationError = error
if error == nil
{
wasSuccessful = true
savedRecords = savedRecords1
}
else
{
wasSuccessful = false
savedRecords = nil
errorCKS = self.handleError(error!)
}
})
ckModifyRecordsOperation.perRecordCompletionBlock = ({(ckRecord,error)->Void in
if error != nil
{
if error!.code == CKErrorCode.ServerRecordChanged.rawValue
{
conflictedRecords.append(ckRecord!)
}
}
})
self.operationQueue?.addOperation(ckModifyRecordsOperation)
self.operationQueue?.waitUntilAllOperationsAreFinished()
if conflictedRecords.count > 0
{
//Do work here
}
else if operationError != nil //Other then the partial error
{
throw operationError
}
}
注意:由于func applyLocalChangesToServer抛出错误并且在while循环中,因此分配了operationError。
答案 0 :(得分:0)
您的假设是正确的,在执行完成处理程序后,将在机箱范围中违反这些变量。所以你的代码应该按预期工作。
您还可以使用以下内容:
ckModifyRecordsOperation.main()
而不是:
self.operationQueue?.addOperation(ckModifyRecordsOperation)
self.operationQueue?.waitUntilAllOperationsAreFinished()
希望它有所帮助。