gpt4 book ai didi

ios - 无法快速附加到局部函数中的全局变量

转载 作者:搜寻专家 更新时间:2023-11-01 05:40:11 26 4
gpt4 key购买 nike

这是我的 View Controller 类

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()

最佳答案

编译器强制您显式调用 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 秒后异步更新(至少对我而言)。因此,您应该在闭包中编写更新代码(用于 TableView ),以确保更新 contacts 数组。

关于ios - 无法快速附加到局部函数中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com