how to get uiview to talk to controller - cocoa-touch

I'm relatively new to Objective-C and Cocoa... I've been trying to understand how to correctly implement the MVC pattern in Cocoa/Cocoa Touch for a long time now... I understand the idea behind it; it makes complete sense conceptually: a model holds the data, a view is what that the user sees and can interact with, and the controller acts as the bridge between the two. View can't talk to the model, model can't talk to the view. Got it.
What doesn't make sense to me is how to use MVC efficiently… if the user can only interact with the view, and does something to interact with it (i.e. for an iPhone app, the user clicks/drags within a subclass of UIView, triggering the "touchesBegan" and "touchesMoved" methods, etc.), how does the view communicate these events to the controller?
I've looked at countless examples and forums online, but have yet to find a simplified all-purpose way of achieving this… I know how to communicate with a controller through buttons, sliders, and other things that you can connect to an outlet, but for things that don't have a target-action mechanism, what's the best way to do it?
Thanks in advance for any suggestions regarding what to do, or where to look.

The standard way in Cocoa to do this is the delegate pattern (cf. UITableViewDelegate). Your view class would declare a delegate protocol and the controller sets itself as the view's delegate. The view then calls one of the delegate methods you defined whenever it wants to communicate something to the controller.
An alternative would be to implement the target-action mechanism for your view yourself. You get this more or less for free if you subclass from UIControl (just call sendActionsForControlEvents:) but it is quite easy to implement a system that works the same way for any custom class.
(Edit: I suppose a third way is to have the controller observe properties of the view (with KVO). This wouldn't work well to communicate touch events but it is a feasible way if you want to notify the controller about a state change or something like that.)

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.

Registering all view controllers for NSNotifications

I have a custom graphic that is to be displayed to a user when an event occurs. The graphic needs to be displayed on whichever viewController is currently being displayed to the user.
The way i have programmed it so far is by adding to ALL viewcontrtollers:
1) the .h file for the custom graphic class
2) an observer for the NSNotification event that is raised
3) the method which actually draws the graphic.
This doesnt feel like a very efficient way of doing things and i was wondering if anyone has a better way of doing things?
To me it sounds like you've done it in a fairly sane way. The only other way I can think is to just add the graphic to the window which would then overlay on the current view controller and you'd only need to have one object listening for the notification. You could use the app delegate for instance. But then you would have to worry about rotation of the screen yourself when adding the graphic over the top.
What you are doing is correct .. The only thing you can improve is to mauve the drawing graphics part to the custom graphic class.. (if you are not already doing so...
just Make a UIViewController variable as a member variable to the graphics class..and then set it up to the current view displaying..after you receive the notifications..and the class will itself draw the code based on the ViewController you set it up to
The reason it doesn't feel efficient is that you're duplicating a lot of code. That's more work at the outset, and it creates a maintenance headache. You should be taking advantage of the inheritance that's built into object oriented languages, including Objective-C.
If you want all your view controllers to share some behavior, then implement that behavior in a common superclass. Derive all your other view controllers from that superclass, and they'll all automatically get the desired behavior. Your superclass's initializer can take care of registering the view controller for the notification(s) that you care about, and -dealloc can unregister it. This way, you don't have to clutter up each view controller with the same repeated code, and if you want to change the code you only have to do it in one place.

iOS Airplay viewcontroller data sychronisation

I've built an iOS 5 iPad app which makes use of a second screen. We have an admin view (on the iPad) and an external view through an HDMI enabled TV connected via the Apple DVI adapter. Both the iPad view and the TV view get the same data updates from a service call which is made every few seconds. We then present the data received as a series of charts; the charted data is presented very differently for the TV and iPad views - but the core dictionary of data is the same. I'm wondering about an elegant way to architect this solution. At the moment I have one of the view controllers (the admin iPad VC) doing the service calls using GCD and then dispatching NSNotifications which update the data (charts) properties on the other (TV) view controller. I'm considering moving the service calls away from the VC and creating a singleton which is initialized in the app controller. I then (somehow) set the two VCs as delegates and they get updated using a simple protocol. I'm not entirely sure if this is a good approach or if I should consider something else? Can I even set both VCs as the delegates of another class or is it typically only one delegate per class instance?
Thanks for any input.
Ben
Why not abstract the chart data into its own model class, which you can share in both view controllers? The model class can be responsible for fetching the new data. To make the controllers aware of updates, they can either use KVO on the model object, or they can observe notifications sent from the model object when an update occurs, or you can have an array of delegates for the model object and each view controller can be a delegate.
There doesn't seem to be any compelling reason to make it a singleton, although you can if you really want.

"Global" UIImagePicker Functionality for Multiple Classes

I'm working on an app that (among other things) uses UIImagePicker to grab an image from the device once the user has selected the SourceType by tapping the appropriate button. Different sections of the app will need to use this functionality, as well as the variable holding the image information once selected. When I first started the project I had all of my code to do this in a single class named ViewController. I'm now working on moving the individual sections of the app into their own classes, but I'd like to be able to have them all use the UIImagePicker functionality from a central location.
Along with the necessary UIImagePickerController methods and protocols, I have a method that presents a view with buttons for each available SourceType. Each of these buttons then send a message to methods to show the appropriate picker (or the camera). Once an image is selected, it is applied to a variable for use by the different sections.
I wanted to get suggestions on the best way to approach this before I went to deep down the wrong rabbit hole.
Thanks!
If a lot of your classes use this functionality, you can create a superclass (itself being a subclass of UIViewController).
This class will expose some method to launch the process you described, and some other to gather the information collected.
If you don't want to use inheritance, or you already to with another class, you can also create a separate class responsible for this process.
This class, which is not necessary a UIViewController, has to be instantiated and then called the same way the superclass described above.

MVC with cocoa/objective-c

I have a strong j2ee background, and I am trying to move to objective-c for some desktop/iphone programming.
I used many java web frameworks with mvc in mind, spring and struts ecc... so I am used to have servlet or controller which pass attributes to jsp pages, which is the view.
In jsp pages with jstl you can call this attribute and render to video.
In this way controller and view are (in theory) clearly separated.
With xcode, I can easily recognize the controller and the view built with IBuilder.
All the tutorial I found, shown the controller which go and change directly labels or text fields.
So my two questions:
seems to me that there's no separation between the two (controller and view), where I am wrong in that ?
is there a way for a controller to pack all objects in a kind of context in a j2ee way and have the view read that context ?
thanks
Leonardo
In most of the examples you have read you probably saw something like this:
[myTextfield setStringValue:myString];
now in this case sure the controller is updating the textfield directly, however as myTextfield is usually an IBOutlet it can be any textfield in your view, or even nil. quite possibiy it doesn't even need to know that it is an NSTextfield just that it responds to a setStringValue method. In this sense there is a seperation between the controller and view.
Now in your comments above you were concerned with seperation of responsibilities within MVC but did not mention the model much. With Cocoa bindings you can bind directly to model keypaths, in this case the model neeed not know anything at all about the view.
MVC is a bit of an ambiguous concept with no hard definition. It can mean different things to different people. For me it means that the view has knowledge of the controller ( through outlets or bindings) limited knowledge of the model(through bindings). The contoller has full knowledge of the model and limited knowledge of the view(through outlets). Finally the model has zero knowlege of the view and ideally no knowledge of the controller.
With regard to your second question, I don't use j2ee, but I think you can acheivee what you want by having your controller update a context ivar ( probably a NSDictionary) then in your view bind to this context with a keypath. However there is no real need to wrap everything up bindings are very versitile and u can bind to any property.
I do not understand your second question (I've never used J2EE), but I think I can make some headway answering your first.
Cocoa does not enforce MVC; it just strongly encourages it -- especially for larger projects. Consider an example program, one that has an NSTableView bound to an NSArrayController.
In this case, the NSTableView is clearly the view (it has the word "view" in its name) and the NSArrayController is clearly the controller (it has the word "controller" in its name).
The model is an NSArray that the NSArrayController knows about, but you probably don't interact with that model directly. You will instead ask the NSArrayController to manipulate its model by sending addObject: and removeObject: messages to the array controller (and not to the array itself).
When you do this, the NSArrayController will effect a change in the NSTableView via bindings. Again, you don't ever ask the NSTableView to do anything.
So you never talk to the view and you never talk to the model. Everything you want to happen goes through the controller.
MVC. QED.
Of course, maybe the way your project works, the view should be its own controller. The world won't end, although you might find it to be a little more difficult to go against the grain of the framework. But you should always try to use the best approach for the job at hand instead of insisting on some sort of design pattern purity.