NSManagedObject subclass woes - cocoa

Hey guys, I've got a subclass of an NSManagedObject. In awakeFromInsert and awakeFromFetch I'm calling an initialization method which, among other things, starts an NSTimer.
Now i need a place to invalidate the timer. However, dealloc, finalize, didTurnIntoFault, prepareForDeletion and willTurnIntoFault aren't getting called.
According to the documentation, these methods should all get called when the object is cleared from memory. None of them are, however all the data is saved in the persistent store. I'm puzzled as to why or how.
Is there anything i could be doing that could cause these methods to not get called during the objects life cycle?

Core data controls the lifetime of NSManagedObjects. It's not going to flush an object from memory by itself unless you ask it to. Looking at the documentation, there appear to be two ways:
sending refresh:mergeChanges: to the MOC causes the object to turn into a fault.
sending reset to the MOC causes it to reset itself as if it has just been created.
However, any of the above requires explicit action on your part, so you might as well add a method to the object to invalidate its timer and invoke that.
In fact, your problem probably indicates a design issue. An NSTimer is essentially a user interface event. It should probably be controlled by your MVC controller which sends a message to the model object (the NSManagedObject) to do the action.

Related

Use PropertyChanged or WeakSubscribe?

What is the best way to track a property change?
I have the following concerns why I can't make a decision.
- PropertyChanged can prevent garbage collection from collecting a ViewModel that uses its own PropertyChanged event?
- Could WeakSubscribe be gone at any moment in time when using to track ViewModels own property changes?
Did anyone test this or just know the answer ?
In general, you won't hit problems if you use PropertyChanged strong subscriptions.... However, there are some cases where this can lead to "leaks" - e.g. if you subscribe on a sub-object which has a longer lifetime than a "normal" ViewModel (e.g. a singleton service).
To be safe, though, you can use WeakSubscribe - as long as you store a reference to the returned token from the WeakSubscribe call in a member field in your view, then this will ensure that the subscription remains active for at least as long as your View is in memory.
Regardless of strong or weak, one additional thing to aim for ... is to try to release the event subscription (either strong or weak) as early as you can. This will help prevent event callbacks being fired after the View has disappeared.

What would be a thread-safe way to save a context form Core Data?

I have a NSOperationQueue set to NSOperationQueueDefaultMaxConcurrentOperationCount. It is filled with NSOperation objects (nothing weird so far). I subclassed the NSOperation to do some background tasks.
Download data from the internet.
Parse the data so I can read it.
Create a NSManagedObject:
[NSEntityDescription insertNewObjectForEntityForName:#"Channel" inManagedObjectContext:context];
Save it with the context.
[managedObjectContext save:&error]
I like this all to happen in the background so the UI won't get blocked. I read this article about concurrency with core data, and as far as I understood it. The best way would be to create a new NSManagedObjectContext in every NSOperation, but share the same persistent store coordinator.
That's easily done, however, when it comes to saving the context it says in the documentation it is error prone to do so. So my question is the following:
If I have different operations running in the NSOperationQueue, could those operations interfere with each other while saving the managed object context? Or does it wait to execute the following operation till the saving has been complete?
Can I safely save the context in a NSOperation? Or is it really bad practice?
I hope someone can shine a light on this matter, because I am really stuck at the moment.
What you need to do is the following:
Create a managed object context for each NSOperation. Create this new context on the main method, because this is when it's executing on the right thread.
Assign the context persistent store coordinator.
Create an observer to receive the NSManagedObjectContextDidSaveNotification. This is the only way the main context will know at the time the changes were made on the NSOperation's context. Make sure the merge call is made on the thread/block the merging context lives in. If you are merging with the main thread's context, call the mergeChangesFromContextDidSaveNotification: method on the main thread with the notification from the NSOperation's context.
Also, ask yourself if you really want to have all these operations working concurrently. Per the documentation:
The default maximum number of operations is determined dynamically by the NSOperationQueue object based on current system conditions.
You do not have control over how many NSOperations will be operating at the same time. If this is not what you want, you might be better if you just go with a serial NSOperationQueue (maxConcurrentOperation=1), considering the fact that you are going to be locking the database to do the save, and also because you have networking being done as well.
You can safely save inside the NSOperation's main method, if you take the precautions mentioned above.

Make NSArrayController fetch after background operation completes

I have a subclass of an NSArrayController linked to a core data model. In one of the methods I call
[self performSelectorInBackground:#selector(someLongExpensiveOperation:) withObject:obj];
which imports a ton of core data objects in the background.
The problem is, unless I manually add a fetch button on the interface and click it after the import operation completes, the array controller doesn't update itself to reflect the new data model. Any ideas on how to force array controller to update?
EDIT:
Turned out I also had some concurrency issues as NSManagedObjectContext is not suppose to be thread-safe. Had to account for that as well and then it started working.
Call prepareContent at the end of your someLongExpensiveOperation: method.

Is NSPasteboard thread-safe?

Is it safe to write data to an NSPasteboard object from a background thread? I can't seem to find a definitive answer anywhere. I think the assumption is that the data will be written to the pasteboard before the drag begins.
Background:
I have an application that is fetching data from Evernote. When the application first loads, it gets the meta data for each note, but not the note content. The note stubs are then listed in an outline view. When the user starts to drag a note, the notes are passed to the background thread that handles getting the note content from Evernote. Having the main thread block until the data is gotten results in a significant delay and a poor user experience, so I have the [outlineView:writeItems:toPasteboard:] function return YES while the background thread processes the data and invokes the main thread to write the data to the pasteboard object. If the note content gets transferred before the user drops the note somewhere, everything works perfectly. If the user drops the note somewhere before the data has been processed... well, everything blocks forever. Is it safe to just have the background thread write the data to the pasteboard?
You can promise the data to the pasteboard without actually having the data yet.
One way is to declare the type of the data on the pasteboard, passing yourself as the pasteboard's owner, and respond to a pasteboard:provideDataForType: message by providing the data (blocking, if necessary, until the data either arrives or fails to arrive). This means that you'll need to remember which objects were copied (by stashing them in an array, for example) so you can extract/generate the data from them when the promise comes due.
The other way, referenced in Harald Scheirich's answer, is to make your model objects conform to the NSPasteboardWriting protocol, ideally in a category (to separate interface-independent logic from Mac-specific logic). This is much cleaner than the old way, but requires Mac OS X 10.6 and later.
With NSPasteboardWriting, you'll implement promises by having the model objects' writingOptionsForType:pasteboard: method return the NSPasteboardWritingPromised option. Their pasteboardPropertyListForType: method will return the data, or at least try to—as before, this method should block until the data either arrives or fails to arrive.
Oh, and to answer the question in the title (“Is NSPasteboard thread-safe?”): There's no specific answer in the Thread Safety Summary, but there is this general statement:
… mutable objects are generally not thread-safe. To use mutable objects in a threaded application, the application must synchronize appropriately.
I would consider an NSPasteboard to be a mutable object, so no.
In practice, this isn't a problem: You typically only work with NSPasteboard in response to an action message (e.g., copy:), a drag, or a service invocation, and those all only happen on the main thread anyway. For them to happen on a secondary thread, you would have to explicitly send such messages yourself from code running on a secondary thread, in which case you are already doing something very wrong.
Conjecture:
I think your problem has nothing to do with threading but the fact that by returning YES you told the system that the data is ready. have you tried moving your data into a custom class supporting NSPasteboardWriting and NSPasteboardReading? this way the accessor to your data can block until the data is ready.
See the Pasteboard Documentation

Delegate not being called

I have a ContactsViewController which -whenever a row is selected- MessageViewController is opened (using pushViewController). Both the ContactsViewController and the MessageViewController 'register' to receive DatastoreDelegate messages. The weird thing is it all works fine upon loading of my application, but once I navigate to the MessageViewController the delegate methods on my ContactsViewController don't get called anymore. Both these controllers should handle the [messageAdded:(Message *)message] method, but only the MessageViewController keeps receiving the messages after it's been opened once.
Does anyone have any idea on how to make this work?
In Cocoa, every object with a delegate has only one delegate (at any given time). That delegate is the only object that gets the delegate messages. There's no real concept of having "both objects registered to receive delegate messages." My suspicion here is that when you push the MessageViewController, it sets itself as the Datastore's delegate, and then the ContactsViewController never sees those messages again, because it doesn't set itself back.
I don't know how your code is structured, but you could simply hand-off the delegate every time the controllers change view so whichever is active is the current delegate.
In Cocoa, the Notification pattern (see NSNotificationCenter) is used when an object needs to "broadcast" information to multiple other objects. Delegates are really what they sound like: an object that another object optionally relies on to "partner with" it and provide key functionality. It's a more intimate relationship than a notification observer.

Resources