oky_sabeni
oky_sabeni

Reputation: 7822

How do I return realm object or create one if empty?

Suppose I have a SearchText object as such:

class SearchText: Object {
    dynamic var text: String = ""
}

I would like to create an accessor such that I can get that object if it exists or create one if it doesn't. This is what I have.

extension Realm {
    var searchText: SearchText {
        if let searchText = objects(SearchText.self).first {
            return searchText
        } else {
            let searchText = SearchText()
            try! write {
                add(searchText)
            }
            return searchText
        }
}

This kinda works but here is my problem. I would like to use searchText and also update its value. Something like:

func updateSearchText(text: String) {
        try! write {
            searchText?.text = text
        }
    }

When I try to updateSearchText, I get a realm exception of Realm is already in a write transaction. I think it's because I'm nesting to writes: creating the text and then updating it.

How would I do this elegantly?

Upvotes: 1

Views: 451

Answers (1)

kishikawa katsumi
kishikawa katsumi

Reputation: 10593

Realm doesn't provide nested transaction currently. There is a way to avoid the exception is check you're in write transaction before open a transaction. Like the following:

func updateSearchText(text: String) {
    func update() {
        searchText?.text = text
    }

    if inWriteTransaction {
        update()
    } else {
        try! write {
            update()
        }
    }
}

Maybe searchText setter also should be:

var searchText: SearchText {
    if let searchText = objects(SearchText.self).first {
        return searchText
    } else {
        let searchText = SearchText()
        if inWriteTransaction {
            add(searchText)
        } else {
            try! write {
                add(searchText)
            }
        }
        return searchText
    }
}

Upvotes: 1

Related Questions