3

将 NSData 变量添加到我的领域模型后出现错误:

致命错误:在展开可选值时意外发现 nil

当我不使用 NSData 值时,不会出现此错误。

这是我的简单项目(Item.swift)

    class Item: Object {
    dynamic var Name: String = ""
    dynamic var Adress:String = ""
    dynamic var image: NSData = NSData()
}

我在返回 dataSource.Count 时收到此错误:

var dataSource: Results<Item>!
let itemDetailSegue = "showItemDetail";
var loadCurrentItem: Item!

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    reloadTable()
}

override func viewDidLoad() {
    super.viewDidLoad()
    reloadTable()
}

// MARK: - Table view data source
func reloadTable(){
    do{
        let realm = try Realm()
        dataSource = realm.objects(Item)
        tableView?.reloadData()
    }catch{
        print("ERROR ReloadTable")
    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataSource.count
}
4

1 回答 1

1

错误消息说需要迁移。

Migration is required due to the following errors: - Property 'image' has been added to latest object model.

有三种方法可以解决此错误。

1.增加架构版本

let config = Realm.Configuration(schemaVersion: 1) // Increment schema version
do {
    let realm = try Realm(configuration: config)

迁移过程需要两个步骤。首先,增加架构版本。然后在迁移块中定义迁移。但是如果是简单的添加/删除属性,自动迁移就可以了。所以你不需要定义迁移块。只需增加架构版本。

2.删除现有应用并重新安装

删除应用程序意味着删除现有的数据文件。因此,下次启动应用程序时,将使用新架构创建一个新数据文件。

3.使用deleteRealmIfMigrationNeeded属性

deleteRealmIfMigrationNeeded为 true 时,如果需要迁移,数据文件将被删除并使用新架构自动重新创建。

let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
do {
    let realm = try Realm(configuration: config)
于 2016-05-16T10:24:41.333 回答