如何在 Swift 中将completionHandler 闭包中的数据深度复制到 ViewController 类?
我尝试过使用 NSCopying 协议和 JSON 解码器/编码器来 DeepCopy 数据,但每次我偶然发现某个地方并且无法修复它。
如何将结果中的所有内容完全相同地复制到类变量 postData 中?我想以编程方式将其添加到表格视图中,但我无法让它工作。
这是 ViewController 类代码:
class ViewController: UIViewController {
var postData:[Post] = []
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
DataLoader.shared.fetchPostData(completionHandler: {
result in
//it prints result here
for x in result{
print(x.id!)
}
self.postData = result
})
//I'd like to print it here
for x in self.postData{
print(x.id!)
}
}
这是 Post 类代码:
import Foundation
struct Post: Decodable{
var userId: Int!
var id: Int!
var title: String!
var body: String!
}
这是 DataLoader 类代码:
import Foundation
class DataLoader: Codable {
//var classData:[Post] = []
static let shared = DataLoader()
func fetchPostData(completionHandler: @escaping ([Post]) -> Void){
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data else { return }
do {
let postsData = try JSONDecoder().decode([Post].self, from: data)
//self.classData = postsData
completionHandler(postsData)
}
catch {
let error = error
print(error.localizedDescription)
//completionHandler(nil)
}
}.resume()
}
}
I've tried to DeepCopy data with NSCopying protocol and with JSON decoder/encoder, but everytime I stumble upon somewhere and can't get it fixxed.
How can I copy exactly the same all of the contents from result to class variable postData? I'd like to add it to tableview programaticly but I just can't get it to work.
Here is ViewController class code:
class ViewController: UIViewController {
var postData:[Post] = []
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
DataLoader.shared.fetchPostData(completionHandler: {
result in
//it prints result here
for x in result{
print(x.id!)
}
self.postData = result
})
//I'd like to print it here
for x in self.postData{
print(x.id!)
}
}
Here is Post class code:
import Foundation
struct Post: Decodable{
var userId: Int!
var id: Int!
var title: String!
var body: String!
}
and here is DataLoader class code:
import Foundation
class DataLoader: Codable {
//var classData:[Post] = []
static let shared = DataLoader()
func fetchPostData(completionHandler: @escaping ([Post]) -> Void){
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data else { return }
do {
let postsData = try JSONDecoder().decode([Post].self, from: data)
//self.classData = postsData
completionHandler(postsData)
}
catch {
let error = error
print(error.localizedDescription)
//completionHandler(nil)
}
}.resume()
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论