Observing model changes with Cocoa Bindings and NSArrayController - cocoa

I've got an NSArrayController bound to a mutable array in my controller, which manages an array of my model objects. The array controller is bound to my UI. It works well.
Now I'm trying to manually observe when a value changes in my model in my controller class (basically I'm marking the changed model as "needsToSave" for later on, but there are a few other tasks I have when it changes).
I've read up on KVO but I'm not entirely sure what I need to be observing... The NSArrayController? The array of objects? each model object itself? Confusion.
Any pointers would be very helpful. Thanks in advance!

In your model item add and remove methods you should start and stop observing of each item in order to know about everything that happens. This will also help you implement undo. If you need sample code I know the Hillegass book covers it (at least 2nd edition did, have checked 3rd edition yet). You could also look for sample code for implementing undo for help.

Related

Core Data: observing nested properties

I have an entity Category in my Core Data model. Category has a to-many relation to Article. Article has a property read, which is a boolean.
I want to observe the number of unread articles (so I can display it in the title).
A first approach would be something like:
[self.category addObserver:self forKeyPath:#"articles.#sum.read" options:NSKeyValueObservingOptionNew context:nil];
But this doesn't work. I can observe the articles collection to see if something is added, and observe all of the elements individually. I can get this working, but I wonder if there is an easier way. Any hints?
(This might be a duplicate of Using KVO to observe changes to a property on an object inside a collection in Objective-C, but I still think there should be a better way).
How precisely do you need to know what changed and when it changed? If your requirements are very simple, you can listen to the NSManagedObjectContextObjectsDidChangeNotification notification and check the userInfo for NSUpdatedObjectsKey. Those objects will return the changes through their -changedValues method.
How do things get added to the articles collection? It probably easiest to simply hook in there directly in stead of using KVO.

Reverse Cocoa bindings and identify the bindings target view?

I have a custom class that exposes an NSString property. In Interface Builder I've bound the title of an NSButton to the property of my custom class.
Is it possible to get a reference to the NSButton instance from within my custom class?
Essentially I'm trying to locate all the user interface elements that are bound to the property in my custom class.
In general, this sounds like an anti-pattern and/or a bad idea. That said, there are a couple of things to bear in mind. Multiple observers could be bound to your property. You can override addObserver:forKeyPath:options:context: and removeObserver:forKeyPath: (and removeObserver:forKeyPath:context:) and then maintain your own array of observers. With that approach I would caution you that you may need to go to extra effort for the array to not retain observers, as traditionally KV observations don't retain the observing object, and you will likely run into leaks/heap growth if you start retaining them by putting them in an NSArray.
The other gotcha with overriding addObserver:... and removeObserver:... is that, without considerable extra work, you wont know if the observation is for a binding or for something else (like, say, a dependent keyPath notification). One possible workaround for that would be to interrogate the observer via infoForBinding: on all exposedBindings on a later runloop pass using performSelector:afterDelay:. (I think I just threw up in my mouth a little bit for suggesting this.)
Relying on private implementation details of the KVO system is not likely to be a good approach, unless your goal is simply to better understand how KVO works, but it sounds like you're actually trying to accomplish something.
Really, this whole approach just feels like a recipe for disaster. It sounds like an MVC violation from the get-go. Why would the model object need to know about the view objects? Whatever you're trying to accomplish here would almost certainly be better accomplished by having the nib be owned by an NSViewController subclass which has IBOutlets for all the UI elements, and properties for the model. That object would then be in a position to more cleanly manage the apparently complex relationship between your view and model objects without runtime trickery. Since you've not elaborated on the ultimate goal of this trickery, it's hard to say what the best approach would be.

How to programmatically retrieve table selection and table row for Core Data app?

I'm trying to make a Core Data app in which when you select one "Player" in a TableView, and a list of all teammates appears in a second tableView, with a column for how many times those two players have played on the same "Team" (another entity).
This has got me completely stuck, because while I know how to fill up a table from a normal array, using ArrayControllers and Core Data has really cluttered up my view of the situation.
How would you approach this?
Yours is a Bindings problem, not a Core Data problem. :-)
You should definitely get a handle on Cocoa Bindings before dealing with Core Data. This is stated in the docs and is very true.
The subject of your question seems to differ from the body, so I'll answer both.
Showing the Teammates
Core Data aside, assume you have a table representing Player instances. Player has one Team. Team has many players. Therefore, it's inferred that an instance of Player has "team.players" (minus itself) as teammates. Whether you're using Core Data to manage the model or not, this is true of the overall relationships.
If you read through and master Cocoa Bindings, you'll find that this is not hard at all to set up using a basic Master/Detail setup (with an extra array controller for the Detail part, for simplicity). Your Master array controller represents all Player instances, while your detail array controller represents the Teammates - or the Master's selection's "team.players" (minus itself).
The Teammates array controller will have its entity and managed object context set up as usual (see the docs). The "contentSet" will be bound to the Master array controller's "selection" controller key, with "team.players" as the model key path.
The trick is to filter out the Master controller's selected player using predicates. This you can do with the array controller's Filter Predicate. Maybe one with a format of "self != %#", where "%#" represents the Master array controller's selection. I'll leave Predicates (a complicated topic unto itself) to you. Remember, you can set them in code ([myController setFilterPredicate:myPredicate]) or by using bindings. Predicates are independent of Core Data as well.
Getting Selection
Since the array controller is in charge of the array the table represents, it's best to ask the array controller what its selection is. One way is to ask its -arrangedObjets for the objects at its -selectedIndexes.
NSArray * selectedObjects = [[myArrayController arrangedObjects] objectsAtIndexes:[myArrayController selectedIndexes]];
You can also ask it for its -selectedObjects. There are differences between these two approaches that are described by the documentation (API reference and conceptual docs) that you should definitely understand, but asking the controller is the most important concept, regardless of whether you use an NSArrayController or some custom controller that conforms to the and protocols.
Disclaimer: Typed hastily after a social Sake evening. Not checked for errors. :-)

Cocoa bindings: custom setter methods?

I'm using Cocoa bindings to manage a table of objects. I understand how bindings work but I've run into a slight problem. Managing the table of objects would be fine and dandy, except that those objects have to manage actual bluetooth hardware. I'm working off of a framework that provides a class representing a connection to this hardware, and have made another "manager" class the makes it key-value compliant. In other words, this manager class has to be able to connect and modify its "connect" status in its properties dictionary, be the delegate of this hardware and modify properties, and update the hardware with changes made.
However, whenever I set new values within the object itself, like in a "connect" method that would change the "connect" key's value to 2 (looking), (i.e. propertiesDict = newDict), the change is not seeming to be picked up by observers that it is bound to. I've looked at the observeValueForKeyPath:ofObject:change:context: in the NSKeyValueObservingProtocol. However, I don't know what to do with the context argument.
I hope that makes sense... but if anyone has any ideas I'd love to hear them.
Your question isn't totally clear, but if I'm understanding it correctly the issue might be because you need to send manual KVO notifications before and after you change a value in the embedded object. For instance, [self willChangeValueForKey:#"connected"]; and [self didChangeValueForKey:#"connected"];.
There are three ways to update a property/attribute in a KVO compatible way:
Using the property setter (specified in #property declaration or generated by #synthesize)
Calling -willChangeValueForKey: and -didChangeValueForKey: before and after you change the property value in any way.
Calling -setValueForKey:

observeValueForKeyPath:ofObject:change:context: doesn't work properly with arrays

I have an object that implements the indexed accessor methods for a key called contents. In those accessors, I call willChange:valuesAtIndexes:forKey: and didChange:valuesAtIndexes:forKey: when I modify the underlying array.
I also have a custom view object that is bound to contents via an NSArrayController. In observeValueForKeyPath:ofObject:change:context: the only value in the change dictionary for the NSKeyValueChangeKindKey I ever see is NSKeyValueChangeSetting. When I'm adding objects to the array, I expect to see NSKeyValueChangeInsertion.
Recreating my view's internal representation of the objects it observes every time I insert a single item -- particularly when I'm bulk loading hundreds of items -- presents quite a performance problem, as you'd imagine. What am I doing wrong that Cocoa seems to think I'm setting a completely new array each time I add or remove a single item?
(Note to all readers: I hate using answers for this, too, but this discussion is too long for comments. The downside, of course, is that it ends up not sorted chronologically. If you don't like it, I suggest you complain to the Stack Overflow admins about comments being length-limited and plain-text-only.)
I don't understand what you mean by implementing array accessors in the view.
Implement accessors, including indexed accessors, for the mutable array property that you've exposed as a binding.
Bindings is built on top of KVO.
And KVC.
All bindings are implemented using observeValueForKeyPath:
Overriding that is one way, sure. The other way is to implement accessors in the object with the bindable property (the view).
My custom view provides a binding that the app binds to an array -- or in this case, an array controller. Accessor methods apply to KVC, not KVO.
Cocoa Bindings will call your view's accessors for you (presumably using KVC). You don't need to implement the KVO observe method (unless, of course, you're using KVO directly).
I know this because I've done it that way. See PRHGradientView in CPU Usage.
Curiously, the documentation doesn't mention this. I'm going to file a documentation bug about it—either I'm doing something fragile or they forgot to mention this very nice feature in the docs.
It absolutely matters that I'm getting a set message on every array update. I wouldn't have posted it as a question if it didn't matter.
There are quite a large number of people who engage in something called “premature optimization”. I have no way of knowing who is one of them without asking.
I have an object that implements the indexed accessor methods for a key called contents. In those accessors, I call willChange:valuesAtIndexes:forKey: and didChange:valuesAtIndexes:forKey: when I modify the underlying array.
Don't do that. KVO posts the notifications for you when you receive a message to one of those accessors.
I also have a custom view object that is bound to contents via an NSArrayController. In observeValueForKeyPath:ofObject:change:context: the only value in the change dictionary for the NSKeyValueChangeKindKey I ever see is NSKeyValueChangeSetting. When I'm adding objects to the array, I expect to see NSKeyValueChangeInsertion.
For one thing, why are you using KVO directly? Use bind:toObject:withKeyPath:options: to bind the view's property to the array controller's arrangedObjects (I assume) property, and implement array accessors (including indexed accessors, if you like) in the view.
For another, remember that arrangedObjects is a derived property. The array controller will filter and sort its content array; the result is arrangedObjects. You could argue that permuting the indexes from the original insertion into a new insertion would be a more accurate translation of the first change into the second, but setting the entire arrangedObjects array was probably simpler to implement (something like [self _setArrangedObjects:[[newArray filteredArrayUsingPredicate:self.filterPredicate] sortedArrayUsingDescriptors:self.sortDescriptors]]).
Does it really matter? Have you profiled and found that your app is slow with wholesale array replacement?
If so, you may need to bind the view directly to the array's content property or to the original array on the underlying object, and suffer the loss of free filtering and sorting.
I call the KVO methods manually for reasons outside the scope of this issue. I have disabled automatic observing for this property. I know what I'm doing there.
I don't understand what you mean by implementing array accessors in the view. Bindings is built on top of KVO. All bindings are implemented using observeValueForKeyPath: My custom view provides a binding that the app binds to an array -- or in this case, an array controller. Accessor methods apply to KVC, not KVO.
It absolutely matters that I'm getting a set message on every array update. I wouldn't have posted it as a question if it didn't matter. I call something like
[[modelObject mutableArrayValueForKey:#"contents"] addObjectsFromArray:hundredsOfObjects];
On every insertion, my view observes a whole new array. Since I'm potentially adding hundreds of objects, that's O(N^2) when it should to be O(N). That is completely unacceptable, performance issues aside. But, since you mention it, the view does have to do a fair amount of work to observe a whole new array, which significantly slows down the program.
I can't give up using an array controller because I need the filtering and sorting, and because there's an NSTableView bound to the same controller. I rely on it to keep the sorting and selections in sync.
I solved my problem with a complete hack. I wrote a separate method that calls the KVO methods manually so that only one KVO message is sent. It's a hack, I don't like it, and it still makes my view reread the entire array -- although only once, now -- but it works for now until I figure out a better solution.

Resources