无法在NSURLConnection函数外部访问Dictionary的内容 [英] Contents of Dictionary not accessible outside of NSURLConnection Function

查看:85
本文介绍了无法在NSURLConnection函数外部访问Dictionary的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受字符串并返回通过URL请求填充的字典的函数.我的函数将字符串分配给使用SwiftyJSON检索的JSON对象.这些属性已更新,但是退出NSURLConnection.sendAsynchronousRequest函数后,将无法访问它们.

I have a function that takes in a string and returns a dictionary that is populated through a URL request. My function assigns strings to JSON objects, retrieved using SwiftyJSON. The properties are updated, but upon exiting the NSURLConnection.sendAsynchronousRequest function, they are unaccessible.

因此,对于1、2和3 println,该数组可以正确打印,但不能在4上打印.这是代码:

So for the 1, 2, and 3 printlns, the array prints out correctly, but not on 4. Here is the code:

func parseJSON(id:String) -> Dictionary<String, JSON> {
    var properties = [String:JSON]()
    var postEndpoint = "http://localhost:3000/properties/\(id)"
    var urlRequest = NSURLRequest(URL: NSURL(string: postEndpoint)!)

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

        if let anError = error {
            println("error calling GET on /properties/\(id)")
        }
        else {
            let post = JSON(data: data)
            if let title = post["name"].string {
                for (index: String, subJson:JSON) in post {
                    properties[index] = subJson
                }
                println("1: \(properties)")
            }
            else {
                println("error parsing response from POST on /posts")
            }
            println("2 \(properties)")
        }
        println("3 \(properties)")
    })
    println("4 \(properties)")
    return ds1Properties
}

同样重要的是要注意4在1、2和3之前打印出来,这使我认为NSURLConnection会在以后被调用,因此返回值在离开parseJSON之前不会被更新.功能.

It is also important to note that the 4 prints out before the 1, 2, and 3, which makes me think the NSURLConnection is called later, so the return value isn't updated before it leaves the parseJSON function.

推荐答案

您需要了解异步的含义以及如何进行异步编程.

You need to learn what asynchronous means and how to program asynchronously.

使用异步代码,每一行不是一个接一个地执行,而是并行执行.

With asynchronous code, each line is not executed one after the other, they are executed in parallel.

当您调用parseJSON()时,它将完成并立即返回,但是在其中,您已调用sendAsynchronousRequest.这将启动另一个并行运行的线程(您知道什么是线程吗?).该线程可能要几秒钟才能完成.因此,步骤1、2和3可能要到步骤4之后几秒钟才能执行.

When you call parseJSON() it will finish and return immediately, but within it you have called sendAsynchronousRequest. This starts another thread running in parallel (do you know what a thread is?). This thread might not finish for several seconds. Therefore steps 1, 2, and 3 might not execute until several seconds after step 4.

您不能将异步函数放在这样的同步函数中,并且不能期望它像正常"函数一样工作.您需要设计代码来处理这种情况,包括调用parseJSON的代码-因为解析可能需要几秒钟,因此代码需要等待.如果您的应用程序具有GUI,那么如果您未正确执行此操作,则整个应用程序将挂起并冻结.

You cannot put an asynchonrous function inside a synchronous function like this and expect it to work like a "normal" function. You need to design your code to deal with this situation, including the code that calls parseJSON - because the parsing might take several seconds so the code needs to wait. If your app has GUI then if you don't do this properly your whole application will hang and freeze.

因此,当您使用异步性编写代码时,必须设计 entire 应用程序以正确处理它.

Therefore when you write using asynchornicity your entire application has to be designed to deal with it properly.

这篇关于无法在NSURLConnection函数外部访问Dictionary的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆