首页 文章

具有NSData变量的Realm对象,在展开Optional值时意外地发现nil

提问于
浏览
3

在我的Realm Model中添加NSData变量后出现错误:

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

我不使用NSData值时不会出现此错误 .

这是我简单的Item(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
}

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)
    

相关问题