gpt4 book ai didi

ios - 其值在 block 内赋值的引用变量

转载 作者:行者123 更新时间:2023-11-30 13:23:08 26 4
gpt4 key购买 nike

您好,对于分配给完成 block 内的外部 ref 变量的值的范围是什么感到困惑。例如,在下面的代码中,操作错误和保存记录的值将在完成 block 之外保留。

    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 循环内。

最佳答案

您的假设是正确的,在执行完成处理程序后,这些在封装范围内定义的变量将被修改。所以您的代码应该按预期工作。

您还可以使用以下内容:

ckModifyRecordsOperation.main()

而不是:

self.operationQueue?.addOperation(ckModifyRecordsOperation)
self.operationQueue?.waitUntilAllOperationsAreFinished()

希望有帮助。

关于ios - 其值在 block 内赋值的引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37538300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com