Re: I think I screwed up Core Data multi-threading rules.
Re: I think I screwed up Core Data multi-threading rules.
- Subject: Re: I think I screwed up Core Data multi-threading rules.
- From: Quincey Morris <email@hidden>
- Date: Thu, 23 Feb 2017 19:43:16 -0800
- Feedback-id: 167118m:167118agYYG0F:167118sezLv_UtzB:SMTPCORP
On Feb 23, 2017, at 18:25 , Daryle Walker <email@hidden> wrote:
>
>> override func save(to url: URL, ofType typeName: String, for saveOperation: NSSaveOperationType, completionHandler: @escaping (Error?) -> Void) {
>> // Save the message data to the store so any background contexts can read the data later.
>> do {
>> try self.container.viewContext.save()
>> } catch {
>> completionHandler(error)
>> return
>> }
>>
>> // Do the usual code, possibly even use a background thread.
>> super.save(to: url, ofType: typeName, for: saveOperation, completionHandler: completionHandler)
>> }
>
> I found out about this method from the Document guide docs. I have two questions about it.
>
> 1. Is it OK to abort your override before the call to super if your pre-super code gets an error?
The catch block you’ve shown seems perfectly reasonable. Unfortunately, the documentation says you can do anything you want before or after, but “be sure to invoke super”, which probably makes you nervous. However, I think you can assume it’s ok to return like that if an error preventing the save occurs. Any other assumption seems too paranoid.
The documentation also says that the completion handler must be invoked on the main thread, and I doubt you can assume that this save function is itself necessarily invoked on the main thread. IAC, it’s only one extra line to invoke the completion handler on the main thread, so I’d do that.
> 2. What should happen if your post-super code (which I don’t have in my example) has an error? Do you drop it to oblivion? Or can you call the completion handler?
Invoking the completion handler a second time sounds like a really terrible idea. I’d strongly advise you to put all your failable code before the super invocation, so the issue doesn’t arise ...
> Note that if the call to super has its own errors, then your post-super code would make the handler be called twice.
… but I think you’re showing a conceptual error here. The super invocation will *always* call the completion handler, error or no error. It’s a completion handler, not an error handler. You can assume that the completion block will involve logic to exit NSDocument’s internal save machinery and state, so a second invocation is will probably crash and burn.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden