将 NSMutableArray 传递给 Swift 中的另一个对象

Passing an NSMutableArray to another object in Swift

我正在进行网络调用并从 API 中检索一些信息并将其存储在 NSMutableArray 中。我在尝试将该数组信息发送到另一个对象时遇到了问题:
我没有任何错误。我无法访问另一个 class 中的数组信息。它在 API class 中打印正常,但是当尝试在另一个 class 中访问时,数组打印为空。

这是我的 API class,最上面有一个 NSMutableArray 来保存信息:

class API: NSObject {

    var informationArray = NSMutableArray();

    func getEarthquakeInformation() {

        let session = NSURLSession.sharedSession()
        let urlString = "http://ehp2-earthquake.wr.usgs.gov/fdsnws/event/1/query?format=geojson&limit=20"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        let task = session.dataTaskWithRequest(request){ data,response,downloadError in

            if let error = downloadError {
                 print("could not complete the request\(error)")
            } else {

                let parsedResult = try! NSJSONSerialization.JSONObjectWithData(data! , options: NSJSONReadingOptions.AllowFragments)
                let dataDict = parsedResult as! NSDictionary

                // This holds all the information we need from the API.
                if let result = dataDict["features"] {

                    for var i = 0; i < result.count; i++ {
                        self.informationArray.addObject(result[i])
                        print(self.informationArray[i]) 
                    }

                } else {
                    print("error")
                }

                //print("info from the array \(self.informationArray)")   
            }  
        }
        task.resume() 
    }
}

这是 class 我正在尝试将其发送至:MapViewController

 override func viewDidLoad() {
        super.viewDidLoad()

        // Instance of the api class
        let apiObject = API()
        apiObject.getEarthquakeInformation()
        print(apiObject.informationArray)

这里有几件事:

首先,请考虑使用网络库(例如AlamoFire

其次,当你声明你的可变数组时,你应该以这种形式来做(没有理由使用 NSMutableArray()):

var myArray = [ObjectType]()

Third,不要使用 C-style for-loops,它们被标记为从 Swift 中删除。你应该迭代:

for item in result {
    //Do something with item.
}

,至于"sending" 数组到您的 MapViewController 对象。 如果 API 对象存在于您的 MapViewController 中,那么您可以让 API 函数将闭包作为参数。您可以将数组传递回闭包本身中的 MapViewController。 或者您也可以使用通知。

希望这对您有所帮助。

  let apiObject = API()
    // Your problem it here this method takes time to update informationArray
    apiObject.getEarthquakeInformation()
    // But this line print immediately while it's still empty.
    print(apiObject.informationArray)

你所做的就是

  • API class 中完全删除 informationArray 并将其放入 MapViewController
  • 更改 getEarthquakeInformation 方法以具有完成处理程序

    class API: NSObject {
    
    // remove it  //var informationArray = NSMutableArray();
    
    func getEarthquakeInformation(compeletion: (informationArray: [AnyObject]!) ->()) {
    
        let session = NSURLSession.sharedSession()
        let urlString = "http://ehp2-earthquake.wr.usgs.gov/fdsnws/event/1/query?format=geojson&limit=20"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        let task = session.dataTaskWithRequest(request){ data,response,downloadError in
    
            if let error = downloadError {
                 print("could not complete the request\(error)")
            } else {
    
                let parsedResult = try! NSJSONSerialization.JSONObjectWithData(data! , options: NSJSONReadingOptions.AllowFragments)
                let dataDict = parsedResult as! NSDictionary
    
                // This holds all the information we need from the API.
                if let result = dataDict["features"] {
                  compeletion(result)
                } else {
                    print("error")
                }
            }    
        }
    
        task.resume()
    }
    

然后在 MapViewController

var informationArray: [AnyObject]!
override func viewDidLoad() {
   super.viewDidLoad()

    // Instance of the api class
    let apiObject = API()
    apiObject.getEarthquakeInformation() { [unowned self] (result) ->() in 
    self.inforamtionArray = result
    print(self.informationArray)
}