swift - 保留循环内的值

标签 swift

我有一个 for 循环,它会遍历我的 URL 记录并发出请求。请求的结果被再次用于上传其他待处理的内容。但我在这一行中收到错误:print("id is\(t.url!)")。我猜当执行该行代码时循环已经完成,这就是它返回 nil 的原因。 您对此有什么建议吗?

let fetchRequest = NSFetchRequest(entityName:"Pending")

                        let company_temp = try context.executeFetchRequest(fetchRequest)
                        let company = company_temp as! [Pending]
                        for t in company {
                            let request = NSURLRequest(URL: NSURL(string:t.url!)!)

                            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                                print("ticket is \(NSString(data: data!, encoding: NSUTF8StringEncoding))")
                                print("id is \(t.url!)")
                                print("id is \(t.id!)")
                                self.upload_sig(NSString(data: data!, encoding: NSUTF8StringEncoding)!, id: t.id!)



                        }

最佳答案

很难说为什么它不起作用,但我猜想托管对象要么不再存在,要么它所在的上下文已被破坏,所以它无法填充它的数据,而你出现错误。

在您的特定情况下,您实际上不需要在处理 URL 请求完成的代码中使用该对象,因此不要将其保留在那里。相反,只捕获您需要的 id 而不是容器:

let request = NSURLRequest(URL: NSURL(string:t.url!)!)
let objectId = i.id!

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    print("ticket is \(NSString(data: data!, encoding: NSUTF8StringEncoding))")
    print("id is \(objectId)")
    self.upload_sig(NSString(data: data!, encoding: NSUTF8StringEncoding)!, id: objectId)

另请注意,您应该使用 !谨慎地检查错误...

关于swift - 保留循环内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696543/

相关文章:

json - Swift 和 Codable : Encodable tree struct terminating in values that obey custom protocol

swift - NSMenuItem 设置状态不起作用

swift - 具体提示用户何时允许推送通知

ios - 在 Swift 中根据纬度和经度查找城市名称和国家/地区

ios - 您是否需要为应用程序中的每个 View Controller 创建一个单独的 .swift 文件?

swift - 在 OpenWhisk 上使用 Swift 发出 HTTP 请求?

multithreading - Swift 有任何本地并发和多线程支持吗?

json - 在 Realm 中导入 JSON

swift - iPhone SE 尺寸屏幕的 Xcode 自动布局问题

swift - 当我单击 UISegmentedControl 时,将其更改为 UITableViewCell