ios - NSUserDefault 自定义对象错误 - "array cannot be bridged from Objective-C"

标签 ios objective-c swift

在包含 return goal//**// 的行上,我的程序崩溃并给出错误:“fatal: array cannot be bridged from 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/

相关文章:

ios - 在 swift 中,有什么方法可以调用 super.methodname 吗?

ios - 当我尝试加载 AdMob 广告时 iPad 崩溃

iphone - 屏幕动画未录制

ios - Firebase下载进度观察器错误Swift 3

ios - UIView纵横比混淆systemLayoutSizeFittingSize

ios - 没有 AVAsset 的纯色的 AVMutableComposition

ios - 如何调整图像大小以适应 tableview 单元格中的 UIImageview

ios - 如何修复 Swift 中的 "ActionSheet of UIAlertController has the conflict constraint"错误

ios - 无法使用 CoreBluetooth 显示配对对话框

ios - 在类 ios 之间发送数据?