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

时间:2015-01-12 06:31:21

标签: ios iphone swift nsdictionary parameter-passing

我想将NSDictionary变量传递给下一个View Controller,但它不起作用 我该如何解决这个问题?这是我的src代码。

//...
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:nil。
函数" 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
        // ...
    }
    // ...
}

2 个答案:

答案 0 :(得分:0)

为什么不使用

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

答案 1 :(得分:0)

请注意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)


        })
    }
})