我正在从一个URL读取json,再次(与ObjectiveC有同样的问题),我的应用程序崩溃了这个值.我没有任何字符串和数字的问题.我可以println(值),但是当我将值分配给UILabel时,它会崩溃.
我用这个方法来读取JSON:
func jsonFromURL(jsonURL: String) -> Dictionary<String,AnyObject> {
var jsonNSURL: NSURL = NSURL(string: jsonURL)
let jsonSource: NSData = NSData(contentsOfURL: jsonNSURL)
var json = NSJSONSerialization.JSONObjectWithData(jsonSource,options:NSJSONReadingOptions.MutableContainers,error: nil) as Dictionary<String,AnyObject>
return json
}
…和此代码将值分配给自定义单元格内的UILabel
func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
var regularTextCell:celda = celda(style: UITableViewCellStyle.Default,reuseIdentifier: "cell")
var cell:celda = NSBundle.mainBundle().loadNibNamed("celda",owner: self,options: nil)[0] as celda
cell.name.text = myJson["list"]![indexPath.row]!["name"] as String
cell.id.text = "id: " + String(myJson["list"]![indexPath.row]!["id"] as Int)
// THIS line crash because some values of adress are <null>
cell.address.text = myJson["list"]![indexPath.row]!["address"] as String
return cell
}
您可以查看JSON的示例:https://dl.dropboxusercontent.com/u/787784/example.json
谢谢!
解决方法
如果对象不是字符串,则会像String一样从语法中获取异常.你可以通过使用对象来避免异常吗?字符串可能导致零被分配到您的文本.
在具体情况下,您可以使用:
cell.address.text = (myJson["list"]![indexPath.row]!["address"] as? String) ?? "default"
在那里我替换为你的?并利用了无合并运算符.