Objective C Callbacks and Notifications - iphone

I'm new to Objective-C and not a full time programmer. I'm beginning to understand the Model-View-Controller design pattern for differentiating the UI from the model. So the user takes an action and the view controller sends a message to the delegate (model). But I'm not sure what the best way to send actions from the delegate back to the view controller.
For example, the user pushes a button, the VC messages the Delegate. That part I understand. Then the delegate takes action, and following that the delegate wants to update the VC (e.g., update a label).
So what I missed (or have forgotten) is how this gets done, while maintaining separation between the UI and the model. I suppose I can use the notification center. Or I think I can just have the view controller pass a callback to the delegate. Or maybe there's another choice I don't know of. Can someone give me a recommendation, please?

I think you're slightly misunderstanding the MVC paradigm. Models should never be delegates of views, since models should have no dependencies or knowledge of any view classes. Typically, a view sends a message to its delegate or target (if you're using target/action), which is usually a controller (often a subclass of UIViewController on iOS). The controller then accesses data from the model and can update any views that need updating. I'd recommend reading the MVC fundamentals guide for a more complete explanation.

Basically you're right, you could do all the notification-related things yourself (i.e. with NotificationCenter) but since we're talking about UI-Stuff here I would greatly recommend you to use IBAction-Methods and IBOutlet-Properties in your code which you can easily connect to UI-Elements respectively their Callbacks in Interface Builder.
A very basic introduction to this topic can be found here:
iPhone SDK Interface Builder basic training
i hope that it is not too basic tough, and that I could lead you on the right track.

First of all delegate is NOT a Model.
Model is something passive that only holds the data (DB, plist, array, dictionary etc.).
While delegate is some set of functions that exist in order to react to some events.
Delegate is more likely to be a view controller in your case.
The view controller should react to user's action.
If the button tap should display some data from your model in some label then view controller should do all the work (receive user's action, take the necessary data from the model and display it on the view...).

Related

Need of Delegation in iPhone Development or Objective C

What is the need of delegation in iphone/ipad development or objective C?
I read so many articles on it. All were telling how to implement the concept, but no one was telling why we need to implement that, in which case we should implement it.
Suppose you want to implement Login functionality in your app ... now you won't show Login screen every time you run your app.. only when it is first started and you don't have a login and password...
So in this case..
Your app starts :
View 1 loads (default view )
You check no Login name is there..
You load a new view..(Login View ) .
User enter his details..you get your login and password...
now you want to go back to default view and load the main app with
the names the user entered in Login View....
Now you will use delegate to pass these information(login details) back to default View..so that it knows..its details. now there are many different ways to do these things...like notification and singleton classes.. but when you want to sent more than 3-4 sets of data.. it is best to use delegates
Think of all the components that iOS and Cocoa provide you with. TableViews, TextFields, PopOvers...etc.
When the developers wrote these components, they couldn't possibly know all the various implementations that us developers were going to create using these components. But we need somehow to communicate with them in a generic way.
These components use delegates. The delegate is an implementation independent way of describing some behaviour that your component can conform to.
When UITableView need to find out what is the height of the rows, the UITableView only needs to know about UITableViewDelegate. It doesn't need to know about MyTableViewController, JohnsTableViewController, BobsTableViewController... etc.
So the delegate is decoupling the component from the implementation and the type.
Decoupling is a good thing. It makes maintaing and changing code a lot easier, and makes code reusable.
Delegation is a simple and powerful pattern in which one object in a
program acts on behalf of, or in coordination with, another object.
The delegating object keeps a reference to the other object—the
delegate—and at the appropriate time sends a message to it. The
message informs the delegate of an event that the delegating object is
about to handle or has just handled. The delegate may respond to the
message by updating the appearance or state of itself or other objects
in the application, and in some cases it can return a value that
affects how an impending event is handled. The main value of
delegation is that it allows you to easily customize the behavior of
several objects in one central object.
SOURCE
Use a delegate if you want to talk to only one object. For example, a
tableView has a delegate - only one object should be responsible for
dealing with it.
Use notifications if you want to tell everyone that something has
happened. For example in low memory situations a notification is sent
telling your app that there has been a memory warning. Because lots of
objects in your app might want to lower their memory usage it's a
notification.
this was an answer posted to my question here
There are two key benefits of delegation: customizing objects without subclassing, and improving encapsulation.
Customization without subclassing is a benefit you get from many of the Cocoa and Cocoa-Touch APIs using the delegate pattern. If they didn't do so, you might have to subclass a UITableView every time you wanted to change its behavior by using different types of cells or a different data source. Instead, you just set the table view's delegate and data source to customize its behavior.
As for encapsulation, the delegate pattern helps you keep the different components of your code separate. For example, if your custom View needs to have some data, it would be bad practice to simply give it access to your Model, or even full access to your Controller. Instead, you'd probably set up some kind of delegate protocol for your View that your Controller would implement. That way your classes know no more about each other than they need to, so that changes in one part would be less likely to break others.

iPhone MVC. Problems with the model

I'm new to programming, iphone application programming in specific. After reading a bunch about MVC I decided to give it a try in a small application. As to my understanding, MVC works like this:
Model: data, manipulating data, retrieving data.
ViewController: formats data from the model (NSDate to specific style), etc.
View: the actual gui.
If this is indeed a correct formulation of basic MVC theory, my confusion lies in how data is passed between the model, VC, and view. Example: if I make calls to twitter and get the data in the model, how do I (correctly) pass this information to the VC for further work. I know that between the VC and View one mostly uses IBOutlets. The Model is my real problem.
In my last app I made an NSString variable in the app delegate so I could access that data from any class. However, I read that this is not the best approach when the app becomes complex because the delegate is in charge of starting, ending the app, not holding data.
I've read of delegation methods, singleton's, NSNotification (which I've used to call methods in other classes). The problem is that I don't really understand how to use these techniques to pass data from the model to other views.
Please let me know if my question is unclear.
If you think about reusability, the main components that can be reused again are your model objects and view objects. They can be moved to different apps and still used properly. Your view controller is what is really specific to your app and where most of the app logic lies.
So in your example, you could have a twitter object that stores information and tweets from a user perhaps. You would create that class with all its functions separately within its own .h and .m file. Then in your view controller, instantiate the twitter class with data that is retrieved and begin using it from within the view controller.
Your view controller is actually retrieving the data but your model object is the one maintaining the data. In this way, you can pass on the model data with your twitter object to other view controllers.
Control over the application resides in the controller, so it is the object that will retrieve or save persisted data, update views with that data, and handle various events. Consider it the glue between the model and the view!
For example, if you were to click on a button to open a new modal view, you'd handle that event in your view controller. In the method that responds to the clicked button, you will create or access the new view controller and present it using presentModalViewController:animated:. If that new view and controller needs data that your current controller has access to, you could set a property in the new controller to refer to the object.

How does the Model talk to the View Controller?

Here is something I just can't get to work....I can make the view controller talk to my custom objects just fine....but how do I send messages to the View Controller from my objects?
A message from myViewController to myObject would look like
[myObject doSomething].
What would the opposite message look like? Does it even make sense to send a message the other way?
Greatly appreciate your help!
You could pass a controller to a model, but often you want models to not depend on views or controllers.
To avoid that, make a protocol that the model wants to talk to and have the view controller implement it and have the model take an instance of the protocol, not the view controller as a property.
I often use NSNotificationCenter to broadcast updates from model objects to interested controllers. For a more tightly bound interaction, consider making a delegate protocol for the model object.
A notification is mostly one way, although the listener could access the model object that sent the notification. There can be any number of interested parties, including none if controllers come and go but the model is persistent.
A delegate is two way, but there can only be one delegate at a time. Usually a delegate is expected to outlive the object it is a delegate to. A delegate might be good for a phase of a model object lifespan that requires extra user input.
Notifications and delegates can be used simultaneously. As with UIApplication, the delegate is usually called before the notification is sent.
Why would you want your model to actively talk to anything in the first place? View controllers are the active managers of the app flow, and initiate communications to the model, not the other way around.
Can you say a more specific example of a situation where you would actually need to do this?
Like you suspect yourself, most of the time it doesn't make sense to send messages “the other way.” But if you really need to do that, an appropriate way to broadcast information “out” from models is notifications. You can have your model send notifications, and view controllers or any other objects can subscribe to those notifications if they care, but there is no tight coupling from model to other app pieces.

iPhone app architecture

considering good design, is it better for each view controller to manager their own connection / networking / loading, or to centralize it in the app delegate, or a separate object?
Context:
I have a multi-tab app, each with a navigation controller, and a number of view controller below. Each view controller is doing networking loading XML and images. Currently, i have it setup that it calls to the app delegate to get the xml asynchronously, processing it, and then calling back the top view controller to display the info, and then launching a separate process of loading the images into an array, and sending callbacks for when each is loaded.
From an architectural view-point, is it better to have more networking code in each of the view controllers or calling back to the app delegate?
Ideas / opinions?
TIA.
It's going to make much more sense to have this in each View Controller, I think. The way you've got it set up now sounds a bit weird - you must either be using delegation so that the App Delegate can speak to each view controller, or you have a ton of references to your View Controllers in your app delegate which you probably don't need. I'd imagine your app delegate is cluttered, and I'm curious as to how you're handling things like if the user decides to stop looking at a particular view before the XML related to that view has been sent back to your app and parsed.
If you're worried about having code duplication in your View Controllers, you can probably mitigate that by using Categories.
In the end though I think it's probably best for domain objects to handle this, and not the View Controllers. For example, in viewWillAppear you get or create an instance of a domain object and kick off a getData method which has the view controller as a delegate. All of the requesting/parsing is done in your domain object and when it's completed, it sends your view controller a getDataDidFinish message or something like that.
When I have a situation like this I tend to create an object that handles all the networking stuff for me. That way I end up being able to write code like:
[netObj getXML:somePlace];
The main reason I like this approach is because it keeps my code base tidy and minimizes duplicated code.

Using iPhone NSNotifications in MVC app

I have an NavigationController based app where the data model is stored in the appDelegate after being fetched using CoreData. The views that display the data all have a pointer to appDelegate so that they can query the model for the required data. They then call methods in the appDelegate in response to user selections.
My question is, doesn't the MVC pattern optimally hide the data from the view? Would it be best practice for the appDelegate (in this case serving as model and controller) to supply the data to the view, and for the view to simply send a notification when there is user input? That would eliminate the need for the view to maintain a pointer to the appDelegate.
You're correct to worry about AppDelegate taking on this role. AppDelegate is an easy place to dump stuff, and it quickly becomes overwhelmed with roles. As you note, it's playing data model, data controller and application delegate. If you're getting to the AppDelegate using [[[UIApplication sharedApplication] delegate], it's especially a problem because it makes it very hard to reuse the view in other programs. It's less of a problem if your view has a delegate ivar that just happens to point to the AppDelegate, but could easily point to some other object.
The view often should have a delegate that it passes UI events to. See UITextField and UITextFieldDelegate for a good example pattern. Views generally don't post NSNotification for this kind of stuff. Conversely, model classes typically work best without delegates in my experience.
I am a huge believer in NSNotification. My programs use them for almost all data that moves up from the model layer. But for actions that move down from the view layer, delegation and direct method calls typically work best.
Its not your view that accesses the data. The controller should be the link between the data and the view. If by view you mean the controller, then that's perfectly fine and basically what MVC is all about.