swift 如何将 NSDictionary 传递给下一个视图控制器

How to pass NSDictionary to next view controller in swift

我想将 NSDictionary 变量传递给下一个视图控制器,但它不起作用。
我该如何解决这个问题?这是我的源代码。

//...
let vc = storyBoard.instantiateViewControllerWithIdentifier("SearchResultView") as SearchResultViewController
vc.testId = index + 1
vc.testDict = testDataReturn(index + 1)
self.navigationController?.pushViewController(vc, animated: true)
//...
func testDataReturn(rid: Int) -> NSDictionary {
    var jsonResult: NSDictionary = NSDictionary()
    let urlPath: String = "[MY TEST SERVER]/test.php"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    var stringPost="test_id=\(rid)" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        var err: NSError

        jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    })

    return jsonResult
}

testId:正常通过,但testDict:无。
函数"testDataReturn"运行良好

class SearchResultViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
    var testId: Int = 0
    var testDict: NSDictionary = NSDictionary()
    // ...
    @IBOutlet weak var searchResultTableView: UITableView!
    // ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchResultTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        NSLog("testDict : \(testDict)") // nil
        // ...
    }
    // ...
}

为什么不用

self.performSegueWithIdentifier("FirstToSecond", sender: dictionary)

在此方法中为第二个 VC 设置字典

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let id = segue.identifier
    if(id == "FirstToSecond"){
        var vc: AnyObject = segue.destinationViewController
        (vc as ViewController).setDictionaryMethod(sender)
    }
}

更新: 您可以使用您的方式将字典传递给第二个 VC 但您应该使用

var testDic : NSDictionary?

而不是

var testDic : NSDictionary = NSDictionary()

请注意NSURLConnection.sendAsynchronousRequest是一个在后台执行的异步方法。当它执行 testDataReturn 函数时,函数将继续执行直到函数结束。所以 jsonResult 将被 testDataReturn 函数返回为空。

请在块 NSURLConnection.sendAsynchronousRequest 内执行 UI 更新。将导航代码移到块内,包括属性设置。

NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

    if error == nil
    {
        jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let vc = storyBoard.instantiateViewControllerWithIdentifier("SearchResultView") as SearchResultViewController
            vc.testId = index + 1
            vc.testDict = jsonResult
            self.navigationController?.pushViewController(vc, animated: true)


        })
    }
})