CoreStore icon indicating copy to clipboard operation
CoreStore copied to clipboard

How to pass newly created object into a variable?

Open Guferos opened this issue 8 years ago • 2 comments

Hi,

It's more question than an issue. I want to create a new object and then immediately assign it into my class variable. This is how I've been doing that:

class StatsController {
    
    private var currentSession : Session?
    
    init() {
        weak var weakSelf = self
        CoreStore.perform(
            asynchronous: { (transaction) -> Session in
                let session = transaction.create(Into<Session>())
                return session
            },
            success: { (transaction) in
                weakSelf?.currentSession = CoreStore.fetchExisting(transaction)
            },
            failure: { (error) in
                print("Failed to create new stats session")
            }
        )
    }
}

It works, however it feels like a lot of code. Is it a correct and only way of returning that object into the main context?

Guferos avatar Feb 07 '18 15:02 Guferos

Yes, this is correct (although the success argument is not really transaction, it's the session instance). It looks verbose because you are doing two things here:

  • Creating an object in a safe transaction
  • Passing it safely to the main thread

You'll see this better if you trim all the syntax stuff:

CoreStore.perform(
    asynchronous: { $0.create(Into<Session>()) },
    success: { [weak self] in self?.currentSession = CoreStore.fetchExisting($0) },
    failure: { _ in print("Failed to create new stats session") }
)

JohnEstropia avatar Feb 08 '18 01:02 JohnEstropia

Glad I've found this! I think documentation would benefit from including this case as it seems pretty ordinary? Passing objects safely and Updating objects kind of imply that, but it's not apparent that the object must be fetched outside the transaction first to be simply accessed. 🤷‍♂️

iby avatar Jan 11 '19 20:01 iby