【问题标题】:Cannot able to append to a global variable in a local function swift无法在局部函数swift中附加到全局变量
【发布时间】:2015-07-24 22:40:59
【问题描述】:

这是我的视图控制器类

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var contact_Table: UITableView!

    var  contacts : [Contact] = [Contact]()
    var conj : [Contact] = [Contact]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.populate()
        // Do any additional setup after loading the view, typically from a nib.
    }

func populate()
    {

        let urlstring = "https://api.myjson.com/bins/25976"

        let url = NSURL(string : urlstring)

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data,response, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), {

                var jsonerror : NSError?

                let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonerror)
                    as! NSDictionary

                if let  list_of_doctors = json["doctors"] as? NSArray{

                    let no_of_contacts = list_of_doctors.count-1
                    for index in 0...no_of_contacts
                    {
                        if let single_contact = list_of_doctors[index] as? NSDictionary{

                            let first_name = single_contact["first_name"] as? String               

                            let last_name=single_contact["last_name"] as? Strin                            

                            let password = single_contact["password"] as? String

                            var contactjson = Contact(online: "online_green_dot.jpeg", type: "iamge_nurse.png", name: first_name!, workplace_image: "hospital.png", designation: password!, workplace: last_name!)
                          contacts.append(contactjson)

                        }
                    }
                }
         })
    }
   task.resume()

即使联系人是一个局部变量,我也无法使用contacts.append()附加数据它要求我使用self.contacts.append()

【问题讨论】:

  • contacts 不是本地的。它是一种财产。 self.contacts 是适当的参考
  • 是的。但是当我这样做时,它会在 for 循环中创建一个新实例,但不会附加到现有的联系人数组
  • 不,这不正确。您是否尝试在异步任务完成之前访问联系人数组?
  • 哦,是的。也许这就是问题所在。现在正在努力。非常感谢

标签: ios json swift global local


【解决方案1】:

编译器强制您显式调用self,因为self强烈 捕获在闭包中(由contacts 隐式捕获)。所以你可以清楚地看到这个调用是对self的隐式引用。这也意味着您应该考虑在捕获列表中将self 设为weakunowned 引用:

// replace weak with unowned if self is always there/ not nil
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { [weak self] (data,response, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), {

请注意,数组会在 0.85 秒后异步更新(至少对我而言)。因此,您应该在闭包中制作更新代码(用于表格视图),以确保 contacts 数组已更新。

【讨论】:

  • 没有。那是行不通的。在运行时,它会在块中创建一个新的联系人变量,我以后无法检索它。
  • @shreshtabm 你怎么知道创建了一个新变量?
  • 我已应用断点。数据将被添加到联系人中,但它是 self.contacts n 它不会在联系人中更新
  • @shreshta bm 看来您访问联系人数组的时间太早了。事实上,数组会在 0.85 秒后更新(至少对我而言)。 (所以我的观点仍然存在并添加了注释)
  • 我无法刷新 tableView。知道在哪里写 tableVeiw.reload() 吗?