Search code examples
swiftrealmnsdataoptional-values

Realm object with NSData variable , unexpectedly found nil while unwrapping an Optional value


I get an Error after adding a NSData variable to my Realm Model:

fatal error: unexpectedly found nil while unwrapping an Optional value

This Error doesn't appear when im not using the NSData value.

This is my simple Item (Item.swift)

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

I get this Error, at return 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
}

Solution

  • The error message said a migration is required.

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

    There are three ways to resolve this error.

    1. Increment schema version

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

    A migration process is needed two steps. First, increment schema version. Then define migration within migration block. But if the case of simple add/delete properties, an auto migration works. So you do not need to define migration block. Just increment schema version.

    2. Delete existing app and re-install it

    Deleting app means deleting existing data files. So next time you launch the app, a new data file will be created with a new schema.

    3. Using deleteRealmIfMigrationNeeded property

    When deleteRealmIfMigrationNeeded is true, the data file will be deleted and re-create with a new schema automatically if a migration is needed.

    let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
    do {
        let realm = try Realm(configuration: config)