分段错误:11与swift

时间:2016-10-17 22:49:05

标签: ios swift xcode nsuserdefaults

我正在尝试使用我的代码来尝试添加一些新功能。在添加新的UserDefaults后,我收到一条错误,上面写着“Segmentation fault:11”并且它标记了我的secondviewcontoller,代码在下面。请帮忙

import Foundation
import UIKit
import SpriteKit
import AVFoundation

protocol DestinationViewDelegate {
}
    var delegate : GameViewDelegate! = nil

var bombSoundEffect: AVAudioPlayer!
var ghost = SKSpriteNode()

class SecondViewController: UIViewController, GameViewDelegate {

var sw = false
let defaults = UserDefaults.standard

@IBAction func one(_ sender: AnyObject) {
        defaults.set(1, forKey: "Sphere")
    print("Ghost one was selected")
}

@IBAction func two(_ sender: AnyObject) {
        defaults.set(2, forKey: "Sphere")
    print("Ghost two was selected")
}

@IBAction func three(_ sender: AnyObject) {
        defaults.set(3, forKey: "Sphere")
    print("Ghost three was selected")
}

@IBAction func four(_ sender: AnyObject) {
        defaults.set(4, forKey: "Sphere")
    print("Ghost four was selected")
}

@IBAction func five(_ sender: AnyObject) {
        defaults.set(5, forKey: "Sphere")
    print("Ghost five was selected")
}

@IBAction func six(_ sender: AnyObject) {
        defaults.set(6, forKey: "Sphere")
    print("Ghost six was selected")
}


@IBOutlet var mySwitch: UISwitch!

@IBAction func switchpressed(_ sender: AnyObject) {

let defaults = UserDefaults.standard


    if mySwitch.isOn{
                defaults.set(true, forKey: "SwitchState")

        if bombSoundEffect != nil {
            bombSoundEffect.stop()
            bombSoundEffect = nil

        }

    }
    else{
        defaults.set(false, forKey: "SwitchState")

        let path = Bundle.main.path(forResource: "Untitled2.wav", ofType:nil)!
        let url = URL(fileURLWithPath: path)


        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            bombSoundEffect = sound
            sound.numberOfLoops = -1
            sound.play()
        } catch {
            // couldn't load file :(
        }

    }


}


override func viewDidLoad() {
    super.viewDidLoad()
    // Keep this part the same
    let defaults = UserDefaults.standard

    if (defaults.object(forKey: "SwitchState") != nil) {
        mySwitch.isOn = defaults.bool(forKey: "SwitchState")
    }

    // Check to see if the switch is off, if so, stop the music

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}


}

enter image description here

1 个答案:

答案 0 :(得分:3)

问题在于这段代码:

@IBAction func one(_ sender: AnyObject) {
    defaults.set(1, forKey: "Sphere")
    print("Ghost one was selected")
}

您发现了编译器错误。尝试解决这个问题:

@IBAction func one(_ sender: AnyObject) {
    defaults.set(1 as Any, forKey: "Sphere")
    print("Ghost one was selected")
}

您需要对所有defaults.set来电进行此操作。我认为这将允许你编译。