Swift SpriteKit:线程1:信号SIGABRT。无法投射SKLabelNode类型的值?

问题描述:

所以我完成了一个项目,当我跑它,它死机了,我得到了主题1:信号SIGABRT错误,我看了看说明,它给了我:Swift SpriteKit:线程1:信号SIGABRT。无法投射SKLabelNode类型的值?

无法投类型的值'SKLabelNode'(0x108ed0b78)改为'Koala_Hop.MCTPointLabel'(0x108091da0)。 (LLDB)

此行的代码:

func loadHighscore() { 
    let defaults = NSUserDefaults.standardUserDefaults() 
    let highscoreLabel = childNodeWithName("highscoreLabel") as! MCTPointLabel //line with error 
    highscoreLabel.setTo(defaults.integerForKey("highscore")) 

真的很困惑,需要帮助搞清楚了这一点!提前致谢!

**EDIT**: The declaration of highscoreLabel: 
     func addPoints() { 
    let pointsLabel = MCTPointLabel(num: 0) 
    pointsLabel.fontColor = UIColor.brownColor() 
    pointsLabel.position = CGPointMake(30.0, view!.frame.size.height - 40) 
    pointsLabel.name = "pointsLabel" 
    addChild(pointsLabel) 


    let highScoreLabels = MCTPointLabel(num: 0) 
    highScoreLabels.position = CGPointMake(view!.frame.size.width - 40, view!.frame.size.height - 40) 
    addChild(highScoreLabels) 

    let highscoreLabel = SKLabelNode(text: "High Score") 
    highscoreLabel.fontColor = UIColor.brownColor() 
    highscoreLabel.fontSize = 16.0 
    highscoreLabel.fontName = "Chalkduster" 
    highscoreLabel.name = "highscoreLabel" 
    highscoreLabel.position = CGPointMake(620, 310) 
    addChild(highscoreLabel) 

    } 
+0

是类型MCTPointLabel名 “highscoreLabel” 的标签? – MaxKargin

+0

你是什么意思? –

+0

是MCTPointLabel类型的节点'highscoreLabel'?编译器认为它是'SKLabelNode' – MaxKargin

改变你的GameScene的声明高分标签内:

let highscoreLabel = MCTPointsLabel(text: "High Score") 

假设MCTPointsLabel从SKLabelNode继承一切会正常工作。你必须确保,如果你强迫类型转换,那么你确实拥有一个类的对象。当你这样说:

let highscoreLabel = childNodeWithName("highscoreLabel") as! MCTPointLabel 

你强制转换的标签为MCTPointLabel,而是因为你的highscoreLabel之前为SKLabelNode实际上宣告,你不能强制转换和收到的错误。

希望这可以帮助,让我知道你是否需要澄清。
编辑:代替试试这个:

var highscoreLabel = MCTPointsLabel(num: 0) 
highscoreLabel.text = "High Score" 
+0

我补充说,但它说“无法找到类型MCTPointLabel的初始值设定项,它接受...” –

+0

哦,你没有实现初始化程序?确定你实现了哪个初始化器? – MaxKargin

+0

林有点困惑。我不认为我有一个初始化程序。 –

显然childNodeWithName("highscoreLabel")不是MCTPointLable。

强制转换(使用!)通常是可以避免的,并且很可能会导致运行时问题。您需要计算出childNodeWithName("highscoreLabel")的可能结果,并确保您处理所有可能性或找到您需要的其他信息。

+0

它不会让我甚至没有! –

+0

带有标签的节点是SKLabelNode而不是MCTPointLabel(在更新后的问题中可见)。这就是演员阵容失败的原因(当你不强求时不允许)。 –