【问题标题】:variable empty with NSDictionnaryNSDictionnary 变量为空
【发布时间】:2015-07-20 23:20:33
【问题描述】:

我正在开发一个 iOS 项目,我想知道如何使用 url 从我的数据库中获取数据。

我尝试了很多代码,但没有任何效果。

我的这部分代码似乎有问题:

let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &err) as? NSArray

如果我将NSArray 放入println,它会给我NSArray,但如果我需要将其放入NSDictionnary,则变量为空并且什么都不会出现。

我如何将NSArray 值放入UITableViewCell 中,而这对as? NSDictionnary 不起作用?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您也不应该断言它是一个数组。 NSJSONSerialization.JSONObjectWithData:options:error: 返回的值取决于 JSON。它可以是数组或字典,具体取决于文档的根目录。

    在您的具体情况下,您显然期望有一本字典,但事实并非如此;这是一个数组。

    我建议您仔细查看您的 JSON 和 JSON 解析教程。您可能需要包含更多的错误处理和自省,以使其在现实世界中可靠地工作。

    【讨论】:

      【解决方案2】:

      尝试这样做:

      //replace
      let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &err) as? NSArray
      
      //with
      let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
      

      然后 print(json) 看看你得到什么样的对象

      这是我用来发出获取请求的一些代码:

          let url = NSURL(string: urlString)
          let session = NSURLSession.sharedSession()
          let task = session.dataTaskWithURL(url!, completionHandler:{
              (data, response, error) in
              if error != nil {
                //Handle error, just for testing I do this:
                  print(error!.localizedDescription)
              } else {
                  let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
                  print(json)
                //use data from json, if it's a dictionary, you can loop through and add objects to an array
              }
          })
          task!.resume()
      

      Here's关于提出请求的答案

      这是一个简单的 cellForRowAtIndexPath 方法,它从一个数组中填充 tableViewCells:

      override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let cell = self.tableView.dequeueReusableCellWithIdentifier("cell")
          let text = self.tableContents[indexPath.row] as! String
      //tableContents is just the array from which you're getting what's going in your tableView, and should be declared outside of your methods
          cell.textLabel?.text = text
          return cell
      }
      

      在 viewDidLoad 中有这个 self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-13
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多