Swift 2 JSON解析但不附加全局值数组

时间:2016-01-22 19:51:05

标签: json swift2

我的问题是:

class BackVC: UITableViewController {

  var strArr = Array<String>()

使用viewDidLoad()函数

初始化此值
override func viewDidLoad() {

  super.viewDidLoad()

  strArr = Array<String>()

并将此Json解析代码写在

之后
   let generalUrl = NSURL(string: "my json address")
    let path = NSURLSession.sharedSession().dataTaskWithURL(generalUrl!) { (data, response, error) -> Void in
      if let dataPath = data {
        do {
          let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataPath, options: NSJSONReadingOptions.MutableContainers)

          if let catArr = jsonResult["categories"] as? NSArray {
            for c in catArr {
              self.strArr?.append(c as! String)
            }
          }
        } catch {
          print("json data read error")
        }
      }
    }
    path.resume()
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell

    print("strArr") or print("\(strArr)") is nil
  }

出了什么问题?

2 个答案:

答案 0 :(得分:2)

喜欢在swift中定义arrays,例如[String]

// define array
var strArr = [String]()

// add item to array
for c in catArr {
   self.strArr.append(c as! String)
}

// get item
let text = self.strArray[indexPath.row]
print("next:\(text)")

答案 1 :(得分:0)

与之前的答案类似......

喜欢像swift一样在swift中初始化数组

var strArr = [String]()

或长手更明确的版本

 `var strArr: Array<String> = [String]()`

alternativley到上面的循环

  // add item to array
 for i in 0...catArr.count-1 {
 self.strArr[i].append(c as! String)
 }