在包含 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

    }
}

最佳答案

您试图将 [Goal] 返回为 [Goal?]。由于数组内容类型不匹配(并且无法匹配),您会收到运行时异常。将返回类型更改为 [Goal],特别是因为您总是会返回一些东西。

关于ios - NSUserDefault 自定义对象错误 - "array cannot be bridged from Objective-C",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26173939/

10-12 07:14