NSUserDefault自定义对象错误 - “无法从Objective-C桥接数组”

时间:2014-10-03 05:56:20

标签: ios objective-c swift

在包含return goal //**//的行上,我的程序崩溃并给出错误:“致命:数组无法与Objective-C桥接”。谁能知道这是什么来的?

func saveGoals (goals : [Goal]) {
    var updatedGoals = NSKeyedArchiver.archivedDataWithRootObject(goals)
    NSUserDefaults.standardUserDefaults().setObject(updatedGoals, forKey: "Goals")
    NSUserDefaults.standardUserDefaults().synchronize()
}

func loadCustomObjectWithKey() -> [Goal?] {
    if let encodedObject : NSData = NSUserDefaults.standardUserDefaults().objectForKey("Goals") as? NSData {
        var encodedObject : NSData? = NSUserDefaults.standardUserDefaults().objectForKey("Goals") as? NSData
        var goal : [Goal] = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObject!) as [Goal]
        return goal //**//
    } else {
        return [Goal]()
    }
}
class GoalsViewController: MainPageContentViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: GoalsTableView!
var goalsArray : Array<Goal> = [] //

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self

        if var storedGoals: [Goal] = loadCustomObjectWithKey() as? [Goal] {
            goalsArray = storedGoals
        }

        //retrieve data.

        if var storedGoalList: [Goal] = NSUserDefaults.standardUserDefaults().objectForKey("GoalList") as? [Goal]{
            goalsArray = storedGoalList;
        }

        var goal = Goal(title: "Walk the Dog")
        goalsArray.append(goal)
        saveGoals(goalsArray)

        self.tableView?.reloadData()

        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableViewAutomaticDimension

    }
}

1 个答案:

答案 0 :(得分:3)

您是否尝试将[目标]作为[目标?]返回。由于数组内容类型不匹配(并且无法匹配),因此会出现运行时异常。将返回类型更改为[目标],特别是因为您总是返回一些东西。