用swift中的Button传递数据

时间:2016-02-24 08:25:11

标签: ios json swift

我尝试将数据从ViewController传递到TableViewPlace.swift使用按钮。当我选择按钮返回时没有什么东西

viViewController

class ViewController: UIViewController {

    struct Country{
        var id :Int
        init(id:Int){

            self.id = id
        }
}
var CountrySelected = [Country]()
var countryArry = NSArray()



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func airAction(sender: AnyObject) {
}


@IBAction func viewPlaceAction(sender: AnyObject) {


    getParsePlaceView()
     // json viewPlace


    performSegueWithIdentifier("viewPlaceSegu", sender: sender)
}

@IBAction func tourAction(sender: AnyObject) {
}
/// Open the page
    // parse json
func getParsePlaceView(){

    let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
    NSURLSession.sharedSession().dataTaskWithURL(url!){ [unowned self] (data , repsonse , error) in
        if error != nil {
            print(error!)
        } else {

            do {
                let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]

                for post in posts {

                    if let id = post["userId"] as? Int{

                     // print(id)

                        let sets = Country(id: id)
                        self.CountrySelected.append(sets)
                    }


                }
                self.countryArry = posts
                print(self.countryArry)// return data and currect

            } catch let error as NSError {
                print(error)
            }
        }
        }.resume()

   print(countryArry) // return nil why??
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    // get a reference to the second view controller
    if segue.identifier == "viewPlaceSegu" {
        if let secondViewController = segue.destinationViewController as? TableViewPlace {

            // set a variable in the second view controller with the String to pass
            print(countryArry)
            secondViewController.tnt = countryArry
        }

    }
}


}

当我print(countryArry)返回nil为什么?

有人可以帮助我或给我一个更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您正在使用此行创建Post对象:

let countryPlace = Post(userid: post["userId"] as! Int, title: post["title"] as! String)

您试图将Posttnt对象传递到您的tableview,这是ViewController类的secondViewController.tnt = Country 变量,这就是您遇到第一个错误的原因:

if let title = tnt.title {
   Country.append(title)
}

然后,如果要将字符串国家/地区添加到可变数组中,则必须执行以下操作:

{{1}}