State Change Monitoring - objective-c

I would like to know if there are any apple Xcode APIs for monitoring state changes before I attempt to build my own. The app I work on changes out several View Controllers. Each controller can have a couple smaller custom views plus the usual check boxes, text fields etc.
The main app needs to know if a view controller or anything on it is edited from its previous state when it is pulled up before it is saved again. We only need to know if the state has changed. The caveat is this: if a user checks a checkbox , that is considered a change of state, but if the user also unchecks the check box, then the state is not changed.
I was looking at the NSUndoManager but I'm nor sure if it will work.
Any suggestions appreciated

There are a couple of approaches:
Implement a centralized "model" object. In this scenario, view controllers would just update properties of this main model object and there's little else you have to do. View controllers would then, in viewDidAppear, check the state of this model object and see if anything changed and act accordingly.
Another approach would be to implement a delegate-protocol pattern, by which the various controllers might have some delegate property that would indicate what object must be informed of data changes. This object that would be the data delegate would be defined to conform to some well defined protocol that indicate how to inform it of the changes.
If, though, you (a) have multiple objects that need to be informed of changes; and/or (b) these changes might happen asynchronously while a view is presented, you need some mechanism to do this notification. The two common approaches would be either with key-value-observing of that model object or by posting a custom notification to the NSNotificationCenter.
To advise you better, we'd need a better sense of the nature of your model object, whether updates are happening asynchronously in the background, etc.

Related

How does user input fit into Apple's MVC pattern?

I'm a little confused about input processing in regards to Apple's MVC pattern. According to Apple, your objects should be divided into model objects (which handle the data), view objects (which display stuff), and controllers (which bind the two and also process events and input). However, many of Apple's native UIKit views — UIScrollView, UIControl objects, etc. — do all the input processing themselves, possibly letting their controllers know about it via delegates and data sources. This really confuses me. In my mind, the sturdiness of the MVC triad depends on both the model and view being fairly dumb (and thus easily swappable). When all the OS-level event complexity is centralized in the controller, you have a very nice separation of concerns. On the other hand, adding input processing to the view seems to turn it into a sort of controller of its own.
Am I missing something here? What's the correct way to think about this?
User Input is part of the View in the MVC pattern. They directly interact with the user and provide their data, either on request or through delegation, to a Controller, which might then use that input to affect changes to the Model.
"Dumb" and "easily swappable" are not necessarily the same thing.
Buttons contain a lot of functionality that we don't want to rewrite in every single controller: tinting of the image to indicate highlighting, allowing for cancellation if the tap strays a certain distance before touch-up, etc. Scroll views contain a lot of physics.
In other words, "which display stuff" is a mischaracterisation of view objects. UIView -- the base class -- just provides event data, but subclasses provide higher-level data such as "the button was tapped" or "the scroll view decelerated to a stop".
One thing to think about is your perspective.
When most of us code, our Model is a data object (maybe backed by files or databases, etc), our View is a UIView (possibly setup/configured in Interface Builder) and our Controller is the UIViewController.
What if you weren't coding an app though? What if your world was a UITableView? You can still have a basic MVC separation. Your Model is represented by the UITableViewDataSource protocol, your View still a UIView with it's setups and configurations and your Controller is the UITableViewDelegate protocol. All the pieces there and even separated, the separation is just different than when using a UIViewController. You can see a practical example of the separation a data change. When you the data in the data source protocol nothing happens. You have to call a reloadData method on Controller bit for the table to realize data was changed.
The smaller the item, the harder it will be to see the MVC pattern. A "button" would be a lot harder to use if it was broken into 3 different objects, but you can use MVC patterning inside a single object to create well encapsulated. A UIButton has it's Model in the form of a both public and private properties, a View (UIView still) and a Controller which is bunch of code that accepts events and makes modifications to the View and/or Model as appropriate.

Using NSManagedObjectContextObjectsDidChangeNotification

In many of my UIViewControllers, I update certain controls based on the state of my data. For example, I might have an edit button on a UITableViewController that should only be enabled when there is one or more items. Or perhaps I want to limit the number of items that can be added, and disable the 'add' button otherwise.
Every time I add or delete an item (or take any other action that can add/remove items), I have to remember to update any controls that might need enabling/disabling. This is trivial for the most part, but doesn't feel comfortable - there is a lot of repetition, and I have to remember to add the calls to updateControlEnabled (or whatever) whenever I add new functionality that might affect the data.
And then I noticed NSManagedObjectContextObjectsDidChangeNotification. Reading the docs, it looks like I can receive a notification whenever something changes in my managed object context. This seems ideal, but I have a few questions:
Is this an appropriate use of
NSManagedObjectContextObjectsDidChangeNotification?
Should I anticipate any performance impact if a controller
subscribes to these and parses each one to see if it needs to update
the UI? I will be checking the userInfo for every change, instead of
only those that I know I will care about.
Where should I subscribe to the notifications? My UIViewController has a
reference to the context, which helps, but I don't know where to
subscribe (loadView? viewDidLoad? init?) such that the view
controller will always have one and only one subscription.
The view controller will continue to receive and process notifications
when it's offscreen - enabling and disabling controls as the
data model is affected from elsewhere. Is this ok?
I guess I'm mostly just wondering if anyone else uses this approach and if so, what their experience is.
Q) Is this an appropriate use of NSManagedObjectContextObjectsDidChangeNotification?
A) Yes - I used it on OSX for a similar purpose.
Q) Should I anticipate any performance impact if a controller subscribes to these and parses each one to see if it needs to update the UI? I will be checking the userInfo for every change, instead of only those that I know I will care about.
A) NO - it will normally be a very small set of objects - ones that were directly changed.
Q) Where should I subscribe to the notifications? My UIViewController has a reference to the context, which helps, but I don't know where to subscribe (loadView? viewDidLoad? init?) such that the view controller will always have one and only one subscription.
A) Well, you cannot affect the UI til the view shows - so probably viewDidLoad or viewWillAppear. The problem with the later is you may get it a few times depending on push/pops, so maybe I'd do it in viewDidLoad.
Q) The view controller will continue to receive and process notifications when it's offscreen - enabling and disabling controls as the data model is affected from elsewhere. Is this ok?
A) Sure - when the view reappears all the elements will be setup correctly.
What you want to do is a classical use of that notification. Just check the thread it comes in on - if its not the mainThread then you want to make all your changes in a block posted to the mainThread.

Is there a standard pattern for managing object state in different Cocoa views and menus?

In a Cocoa application is there a standard pattern for keeping UI and other element states in sync? For example I have the main Menu managed by one class and a toolbar managed by another. Some of the menu items must reflect current selections in the toolbar and vice versa. I was going to handle this by having the selector triggered by the menu items and toolbar items fire off a Notification. The controlling classes would subscribe to these an update the UI to match the selection. Is this a good way to do this or am I missing some other natural way to do this in Cocoa?
For the specific case of whether an item should be enabled or disabled, that should be left to the target (or the implicit target if the target is the first responder). It should use User Interface Validation for that.
Bindings is another good technique. The state which governs the UI should either be in the model or the controller, and the UI should bind to it. (If the UI is to bind to the model, it should be through the controller.) That way, you only have to make sure the state is up-to-date and consistent and everything else happens automatically.
But then the technique you describe is a good third option. The model should provide notifications (through NSNotifications or a delegate) to the controller layer when it has changed. The controller layer watches those and has intimate knowledge about what effect state changes should have on the UI and explicitly configures the UI to conform.

Handling notifications in view controller or a subview

I wonder what the optimal way is to respond to notifications sent out by the notification centers.
Here is an example:
I have a model which receives updates from the server.
Whenever new information is received a notification is generated and posted though the NSNotificationCenter.
There is a view controller with lots of (partially nested) subviews; depending on the type of information received I have to update a particular subview.
For me, there are currently two solutions:
The view controller becomes observer and tells a particular view to update based on the notification name. [subviewx pleaseUpdate];
Each view registers an a observer and depending on the notification name.
The downside of 1 is that the vc has to deal with all notifications although he is not really affected.
Is there any proposed way to do this? Should the responsible view controller deal with all notifications or is it ok for a UILabel, for instance, to become an observer and be somewhat independent.
Thanks for your opinion!
An interesting question - technically, both approaches produce the same result.
However, personally I'd lean towards keeping your notification handling in the view controller, because that's closer to the model-view-controller (MVC) pattern in iOS.
The other advantage of having your notification in the view controller is that you may want to reuse your views elsewhere in your app, and you don't want adverse side effects happening when views start responding to notifications they weren't intended to receive. Collating all your notifications in the view controller will also make handling them much easier - don't forget you need to remove your notification observers when you're done with the view, and having all your removeObserver statements in one place is arguably far better than spread across multiple classes.

How to keep model & controller separate from a CALayer based UI?

I'm trying to re-implement an old Reversi board game I wrote with a bit more of a snazzy UI. I've looked at Jens Alfke's GeekGameBoard code for inspiration, and CALayers looks like the way to go for implementing the UI.
However, there is no clean separation of model and view in the GeekGameBoard code; the model is the view, which makes it hard to, for example, make a copy of the game state in order to perform game-tree search for the AI player. However, I don't seem to be able to come up with an alternative way to structure that allows a separation of model and view that doesn't involve a constant battle to keep two parallel grids (on for the model, one for the view) in synch. This, of course, has its own problems.
How do I best best implement the relationship between an AI search-friendly model structure and a display-friendly view? Any suggestions / experiences would be appreciated. I'm dreading / half expecting an answer along the lines of "there is no good answer: deal with it as best you can" but I'm prepared to be surprised!
Thanks for the answer Peter. I'm not entirely sure I understand it fully, however. I can see how this works if you just have an initial set of pieces that are moved around, and even removed, but what happens when a person puts a new piece down? Would it work like this:
User clicks in the view.
View click is translated to a board location and controller is notified.
Controller creates a new Board with the successor state (if appropriate, i.e. it was a legal move).
The view picks up the new board via its bindings, tears down the existing view/layer hierarchy and replaces it with the current state.
Does that sound right?
PS: Sorry for failing to specify whether it was for the iPhone or Mac. I'm most interested in something that works for the iPhone, but if I can get it to work nicely on the Mac first I'm sure I can adapt the solution to work on the iPhone myself. (Or post a new question!)
In theory, it should be the same as for an NSView-based UI: Add a model property (or properties), expose it (or them) as bindings, then bind the view (layer) to the model through a controller.
For example, you might have a Board class with Pieces on it (each Piece having a reference to the Player who owns it), with all of those being model classes. Your controller would own a Board, and your view/layer would be able to display a Board, possibly with a subview/sublayer for each Piece.
You'd bind your board view/layer to the controller's board property, and in your view/layer's setter for that property, create a subview/sublayer for each piece, and bind it to any properties of the Piece that it will need. (Don't forget to unbind and remove all the subviews/sublayers when replacing the main view/layer's Board.)
When you want to move or modify a Piece, you'd do so using its own properties; these will translate to property accesses on the view/layer. Ostensibly, you'll have your layer's properties set up to animate changes (so that, for example, changing a Piece's position will cause the layer for it to move accordingly).
The same goes for the Board. You might let the user change one or both tile colors; you'll bind your color well(s) through your game controller to its Board object, and with the view/layer bound to the same property of the same Board, it'll pick up the change automatically.
Disclaimers: I've never used Core Animation for anything, and if you're asking about Cocoa Touch instead of Cocoa, the above solution won't work, since it depends on Cocoa Bindings.
I have an iPhone application where almost all of the interface is constructed using Core Animation CALayers, and I use a very similar pattern to what Peter describes. He's correct in that you want to treat your CALayers as if they were NSViews / UIViews and manage their logic through controllers and data via model objects.
In my case, I create a hierarchy of controller objects which also function as model objects (I may refactor to split out the model components). Each of the controller objects manages a CALayer, so there ends up being a parallel CALayer display hierarchy to the model-controller one. For my application, I need to perform calculations for equations constructed using this hierarchy, so I use the controllers to provide calculated values from the bottom of the tree up. The controllers also handle user editing events, such as the insertion of new suboperations or deletion of operation trees.
I've created a layer-hosting view class that allows the CALayer tree to respond to touch or mouse events (the source of which is now available within the Core Plot project). For your boardgame example, the CALayer pieces could take in the touch events, and have their controllers manage the back-end logic (determine a legal move, etc.). You should just be able to move pieces around and maintain the same controllers without tearing everything down on every move.