【问题标题】:Swift - Code not returning array value for outside closureSwift - 代码不为外部闭包返回数组值
【发布时间】:2019-01-02 23:42:44
【问题描述】:

我的 swift 代码有问题。我试图在任务关闭之外获取 yearsLinks 数组的值,但我无法这样做,因为它返回一个空数组,我理解这是因为代码在完成关闭之前运行 print(yearsLinks) 代码。

我需要关于我需要做的事情的帮助,有些人建议使用异步,但我不确定我应该在哪里以及如何实现它。

请帮忙 我想设置数组值,yearLinks 到表格视图中的单元格。

这是我的代码的 sn-p。感谢帮助。非常感谢:)

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var url = String()
var yearsLinks = [String]()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return yearsLinks.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
    cell.textLabel?.text = yearsLinks[indexPath.row]
    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if let requests = URL(string: url){
        let request = NSURLRequest(url: requests)
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            if error != nil {
                print(error as Any)
            } else {
                if let unwrappedData = data {
                    let wrappedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

                              ...
              //  THESE ARE JUST CODE TO GRAB THE ARRAY THAT I WANT
              //  linkyears IS AN ARRAY OF VALUES DECLARED IN THE CLOSURE THAT I WANT TO SET TO THE yearsLinks VARIABLE DECLARED OUTSIDE.          
                        self.yearsLinks = linkyears
                              ...

                        print(self.yearsLinks) // THIS WORKS FINE AND RETURNS AN ARRAY OF VALUES THAT I WANTED.
                    }
                }
            }

        }
         // print(yearsLinks)
        // TRYING TO ACCESS THE ARRAY OF VALUES IN THE yearsLinks ARRAY ABOVE RETURNS AN EMPTY STRING??

        task.resume()

    }
}

}

【问题讨论】:

  • 你实际上想在闭包之外用数据做什么?

标签: swift uitableview asynchronous networking closures


【解决方案1】:

获取完成块内的数据后,需要重新加载表格视图。

if let unwrappedData = data {
    let wrappedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

              ...
        DispatchQueue.main.async {
            self.yearsLinks = linkyears
            print(self.yearsLinks)
            self.tableView.reloadData()
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多