【发布时间】:2014-10-02 16:46:45
【问题描述】:
我已经解析了一个 JSON 数组并提取了一个 NSDictionary 并从中提取了一个 String 变量并通过 segue 成功地将它传递给我的下一个视图。当我尝试对整数执行相同操作时,应用程序崩溃...
这是我的代码:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "genreSegue" {
println("genreSegue")
let indexPath = self.tableView.indexPathForSelectedRow()
println("row: \(indexPath.row)")
var bookView:BookViewController = segue.destinationViewController as BookViewController
if let genres = self.genreList as? [NSDictionary] {
var item = genres[indexPath.row]
println("segueItem: \(item)")
let title:String = item["title"] as String
let genreId:Int = item["id"] as Int // this line crashes the app
let genreId:NSNumber = item["id"] as NSNumber // this version also crashes
println("title: \(title)")
bookView.genreTitle = item["title"] as String
//bookView.genreId = item["id"] as Int // so I can't test this line
}
}
}
这是控制台输出:
genreSegue
row: 1
segueItem: {
id = 2;
records = 1;
selfLink = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/id/2";
title = Biography;
}
title: Biography
这是线程 1 上的错误: libswift_stdlib_core.dylib`swift_dynamicCastObjCClassUnconditional:
这里是原始的json数据:
http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list
这是我的应用程序源代码:
https://github.com/marktyers/ios_bookshop_client
我看不到字符串变量是如何工作的,但不是 int。有什么想法吗?
【问题讨论】:
-
或许,崩溃报告和实际的 JSON 会提供更多信息。 ;)
-
盲射远:
NSJSONSerialization给你一个NSNumber对象。也许您正在尝试将其分配给原始Int? -
很好,但是修改了我的代码,如果我使用 NSNumber,我会遇到同样的崩溃......
-
如果您尝试使用
Int()(而不是as Int)转换它会发生什么?
标签: ios json dictionary swift