0

因此,出于演示目的,我从我的 xcassets 中访问了一组图像。我试图使用解析框架一次将 150 张图像保存到我的解析服务器。这是我到目前为止的代码。我遇到的问题是我的应用程序 cpu 在测试中达到 100% 并下降到 0。图像也没有保存以进行解析。我希望有人可以帮助我找到一种有效的方法来保存 150 张图像进行解析。

var imageNameList: [String] {
    var imageNameList2:[String] = [] //[NSMutableArray]()
    for i in 0...149 {
        let imageName = String(format: "pic_%03d", Int(i))
        imageNameList2.append(imageName)
    }
    return imageNameList2
}
@IBAction func Continue(_ sender: Any) {
        for imageName in imageNameList {
            var objectForSave:PFObject = PFObject(className: "Clo")
            let object:UIImage = UIImage(named: imageName)!
            let tilesPF = imageNameList.map({ name in
                let data = UIImagePNGRepresentation(object as! UIImage)!
                let file = PFFile(data: data)

                let tile = PFObject(className: "Tile")
                tile["tile"] = file
            })

            objectForSave["tiles"] = tilesPF

            objectForSave.saveInBackground(block: { responseObject, error in

                //you'll want to save the object ID of the PFObject if you want to retrieve a specific image later
            })


        }

}
4

1 回答 1

1

问题在于紧密的 for 循环会同时启动所有这些请求,从而导致 http 堆栈的某些部分成为瓶颈。

相反,按如下顺序运行请求(以我对 Swift 的最佳近似)...

func doOne(imageName: String, completion: (success: Bool)->()) {
    var objectForSave:PFObject = PFObject(className: "Clo")
    let object:UIImage = UIImage(named: imageName)!
    // ... OP code that forms the request
    objectForSave.saveInBackground(block: { responseObject, error in
        success(error == nil) 
    })
}

func doMany(imageNames: Array<String>, completion: (success: Bool)->()) {
    if (imageNames.count == 0) return completion(YES)
    let nextName = imageNames[0];

    self.doOne(imageName:imageNames[0] completion: {(success: Bool) -> Void in
        if (success) {
            let remainingNames = imageNames[1..imageNames.count-1]
            self.doMany(imageNames: remainingNames completion:completion)
        } else {
            completion(NO)
    })
}

在英语中,以防万一我搞砸了 Swift,我们的想法是使用完成处理程序将单个请求分解到它自己的函数中。构建第二个函数,该函数接受网络请求的参数数组,并像使用待办事项列表一样使用该数组:执行列表中的第一项,当它完成时,递归调用自身以执行剩余的项。

于 2017-03-06T04:23:06.543 回答