将AnyObject强制转换为NSMutableDictionary时,Swift类强制转换失败

时间:2015-02-01 10:03:03

标签: class swift nsmutablearray classcastexception

var fetchEachStory = Firebase(url: "\(self.individualStoryUrl)\(eachStory)")

// Read data and react to changes
fetchEachStory.observeEventType(.Value) {
    snapshot in
    let storyDetails = snapshot.value as NSMutableDictionary?
    let score = storyDetails!["score"] as Int?
    var thisStory = eachStory
    if score? > self.minSetScore {
        self.showStories[thisStory] = storyDetails
    }              
}

在为故事详情分配Snapshot.value时,有时会说:

error: Execution was interrupted, reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
The process has been returned to the state before expression evaluation.

我该如何处理?

2 个答案:

答案 0 :(得分:1)

这行代码:

let storyDetails = snapshot.value as NSMutableDictionary?
如果snapshot.value不是NSMutableDictionary,则

会失败。最好使用条件转换as?以及可选绑定if let,以确保只有snapshot.value是您期望的类型才能继续。 scoreInt也是如此。

根据the Firebase Documentation

  

     

以本机类型的形式返回此数据快照的内容。

     

@property(强,只读,非原子)id值返回值数据   作为本土对象。

     

讨论将此数据快照的内容作为本机类型返回。

     

返回的数据类型:* NSDictionary * NSArray * NSNumber(也是   包括布尔值)* NSString

     

在FDataSnapshot.h中声明

因此,您应该检查NSDictionary而不是NSMutableDictionary

我建议:

// Read data and react to changes
fetchEachStory.observeEventType(.Value) {
    snapshot in
    if let storyDetails = snapshot.value as? NSDictionary {
        // We know snapshot.value was non-nil and it is an NSDictionary.
        if let score = storyDetails["score"] as? Int {
            // We know "score" is a valid key in the dictionary and that its
            // type is Int.
            var thisStory = eachStory
            if score > self.minSetScore {
                self.showStories[thisStory] = storyDetails
                self.tableView.reloadData()
            }
        }
    }              
}

答案 1 :(得分:0)

我发现了这个错误,它更多地与FireBase FDataSnapshot有关,应该使用snapshot.exists()检查快照是否为nil

var fetchEachStory = Firebase(url:"\(self.individualStoryUrl)\(eachStory)")
            // Read data and react to changes
            fetchEachStory.observeEventType(.Value, withBlock: {
                snapshot in
                if snapshot.exists(){
                    let storyDetails = snapshot.value as NSDictionary?
                    let score = storyDetails!["score"] as Int?
                    var thisStory = eachStory
                    if score? > self.minSetScore{
                        self.showStories[thisStory] = storyDetails
                        self.tableView.reloadData()
                    }
                }

            })