How to pass newly created object into a variable?
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?
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") }
)
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. 🤷♂️