swift ios:类似数据的不同错误..非常奇怪

时间:2014-08-30 09:49:11

标签: ios uitableview swift

发生了一些奇怪的事情。

我在TableDataArray中有这个:

(
    {
        count = 0;
        title = Open;
    },
        {
        count = 20;
        title = Closed;
    },
        {
        count = 0;
        title = Pending;
    },
        {
        count = 10;
        title = Queue;
    }
)

当我这样做时:

var rowData: NSDictionary = TableDataArray[indexPath.row] as NSDictionary

var maintext: String?  = rowData["title"] as NSString
println(maintext)

if (maintext  != nil ){
    cell.textLabel.text = maintext
}

它有效,我看到表格中的标题。

但是一旦我添加这些行:

var detailtext: String?  = rowData["count"]  as NSString ## tried also as Int, NSInteger, similar fate

println(detailtext)

if (detailtext != nil)  {
    cell.detailTextLabel.text = detailtext
}

应用程序因“ Swift动态广告失败”而崩溃,我无法弄清楚原因。

另一个是如果我进行另一个API调用,那里的结果是相似的,但它不是崩溃,而是显示文本和详细文本。

然而在另一个api调用中,它崩溃了,但是'致命错误:在解开一个Optional值时出乎意料地发现了nil '...而在另一个中,它只是说String不可转换到Uint8 ......

这让我烦恼。相同的API调用,类似的结果,但它在一个,并崩溃与不同的结果......

所以问题是,如何检测并解决此类问题,然后显示detailText ...因为值存在。

感谢。

2 个答案:

答案 0 :(得分:1)

您的值不能是IntString,因为NSDictionary中的值必须是对象。您的countNSNumber,它是基本数字类型的对象包装。

要安全地从NSDictionary中提取数字,请使用此样式:

if let count = rowData["count"] as? NSNumber {
    // If I get here, I know count is an NSNumber.  If it were some other type
    // it wouldn't crash, but I wouldn't get to this point.

    cell.detailTextLabel.text = "\(count)"
}

这可以保护您免受一系列问题的困扰。当您要求NSDictionary中的项目时,字典中可能不存在该键,在这种情况下,结果将为nil。如果您尝试将其直接转换为预期类型,则会出现致命错误:在展开“可选值”消息时意外发现nil。使用上面的样式,nil处理得很好,没有错误结果,你只是不输入块。

您的count似乎可以有各种类型。您可以使用switch以更清晰的方式处理此问题:

switch rowData["count"] {
case let count as NSNumber:
    cell.detailTextLabel.text = "\(count)"
case let count as NSString:
    cell.detailTextLabel.text = count
case nil:
    println("value not in dictionary")
default:
    println("I still haven't identified the type")
}

答案 1 :(得分:0)

这有效:

    if let maintext = rowData["title"] as? NSString {
        println(maintext)
        cell.textLabel.text = maintext

    }

    if var count = rowData["count"] as? NSNumber {
        // If I get here, I know count is an NSNumber.  If it were some other type
        // it wouldn't crash, but I wouldn't get to this point.
        println("\(count)")
        cell.detailTextLabel.text = "\(count)"


    }

    if var count = rowData["count"] as? String {
        // If I get here, I know count is an NSNumber.  If it were some other type
        // it wouldn't crash, but I wouldn't get to this point.
        println(count)
        cell.detailTextLabel.text = count


    }

但这是正确的方法吗?