Swift:在For-Loop中处理不同的运行时

时间:2017-07-15 11:47:52

标签: swift for-loop synchronization runtime

如何在完成可选服务器请求之前阻止swift跳转到下一个循环?

我正在提取与个人资料相关的访问列表。某些配置文件已经在coreData中,其他配置文件需要向服务器发送其他请求。如何同步这些可能的差异。

在我当前的代码中,当Profile.fetch()返回一个对象时,以下循环已经改变了访问。

var visit: Visit?
let visitFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Visit")
var persistantVisits: [Visit]?
let profileFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Profile")
var persistantProfiles: [Profile]?


for visitDict in json {

    visit = nil
    persistantVisits = []
    persistantProfiles = []

    do {
        visitFetchRequest.predicate = NSPredicate(format: "uuid = %@", visitDict["uuid"] as! CVarArg)
        let persistantVisits = try context.fetch(visitFetchRequest) as? [Visit]

        if persistantVisits?.isEmpty == false {
            // update existing VisitObject in tmp context store
            visit = persistantVisits?[0]
        }
        if visit == nil {
            // create new VisitObject
            visit = NSEntityDescription.insertNewObject(forEntityName: "Visit", into: context) as? Visit
            visit?.uuid = visitDict["uuid"] as? String
        }
    } catch { os_log("/profiles/visits jsonError", log: OSLog.default, type: .error) }

    // fetch Profile
    profileFetchRequest.predicate = NSPredicate(format: "uuid = %@", visitDict["visitor"] as! String)
    persistantProfiles = try context.fetch(profileFetchRequest) as? [Profile]

    if persistantProfiles?.isEmpty == false {
        // update existing ProfileObject
        visit?.profile = persistantProfiles?[0]
        // TRIGGER NEXT LOOP
    } else {
        // create new ProfileObject
        // needs an additional request to the server (visit might be changed by next for loop)
        Profile.fetch(uuid: visitDict["visitor"] as! String, context: context) { (profile) -> () in
            visit?.profile = profile
            // TRIGGER NEXT LOOP
        }
    }
}

是否有某种触发器可以通过代码启动下一个循环?

0 个答案:

没有答案