【问题标题】:Can't retain array data outside of method in SWIFT无法在 SWIFT 中的方法之外保留数组数据
【发布时间】:2015-07-17 09:30:09
【问题描述】:

我使用 alamofire 将 JSON 中的类别名称存储在一个数组中。

数组只有在被这个方法CategoryNameFunc调用时才有值。

如果我从 tableview 或任何其他方法调用数组,它总是 returns 0

代码

    var CategoryNameArray : [String] = []

        override func viewDidLoad() {
            super.viewDidLoad()
            Network()
            tester()
        }

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return CategoryNameArray.count     // This returns 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell : UITableViewCell = self.TableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

    println(self.CategoryNameArray[indexPath.row])

    cell.textLabel?.text = "Hello"

    return cell
}


        func Network(){
            Alamofire.request(.GET, "http://www.wive.com/index.php/capp/category_list")
                .responseJSON { (_, _, data, _) in
                    let json = JSON(data!)
                    let count = json.count
                    self.CategoryNameFunc(json, Count: count) }
        }

        func CategoryNameFunc(Json: JSON, Count: Int)
        {
            for index in 0...Count-1 {
                let name = Json[index]["CATEGORY_NAME"].string
                CategoryNameArray.append(name!)
            }
            // This returns 23 (The correct value)
               println(self.CategoryNameArray.count)
        }

【问题讨论】:

  • stackoverflow.com/help/how-to-ask 有礼貌,不要使用!如果您需要其他人的帮助。
  • @robertvojta 对不起。我已将其删除...
  • 只需将 CategoryNameFunc 中的 println 替换为 self.tableView.reloadData()。通知 tableView 有关更改 - 重新加载。

标签: ios arrays swift swift-playground


【解决方案1】:

当您调用 Network() 函数时,它会创建一个新线程(Alamofire 启动异步请求)并且您的 tester() 函数不会等待您的 Network() 函数完成,然后再计算您的 CategoryNameArray()。但是您的 @ 987654325@函数等待网络操作完成。

【讨论】:

  • 请看编辑
【解决方案2】:

我不确定(没有使用 Almofire),但它认为,这是因为方法 Network,更准确地说是 Almofire 请求是异步触发的。

所以,Network()tester() 方法是同时运行的,但是因为 Network() 需要先获取数据,所以 tester() 速度更快,并被先执行。

依次执行tester()Network() 的正确方法是:

   func CategoryNameFunc(Json: JSON, Count: Int)
    {
        for index in 0...Count-1 {
            let name = Json[index]["CATEGORY_NAME"].string
            CategoryNameArray.append(name!)
        }
        // run tester, AFTER you have the data.
        tester()
    }

【讨论】:

  • 我有一个表格视图,我想在其中列出这些类别。但它显示 Array 超出范围!
  • 在获取数据后尝试重新加载tableview - 在上面的方法中调用tester() ,尝试调用:tableView.reloadData() (tableView 是对tableView 的引用)
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多