The concept of file's owner,first responder, and application delegate in iPhone [duplicate] - iphone

This question already has an answer here:
Closed 13 years ago.
Possible Duplicate:
iPhone Interface Builder and Delegates
What is the relationship between these three component in the Objective C / iPhone world? I found that the App Delegate have some relationship with the UI and the variable in code. It match the variable and related UI object on the view. But I found that the File's owner have the outlet called delegate that related to the Application delegate, what is their relationship. Also, the first responder, it seems it just receive some effect only. What's going on between there stuff?

One at a time:
File's Owner: This is the object that loads the xib file. In a completely generic sense, this is the object passed as the owner parameter to -[NSBundle loadNibNamed:owner:]. When working with a nib for a UIViewController subclass, this is usually the UIViewController subclass itself. Further reading: Resource Programming Guide: Nib Files
First Responder: This is the view that receives untargeted events (i.e. those sent with a target of nil) first. The useful part of this is that it's connected to the idea of the responder chain, which is a mechanism by which things higher up in the view hierarchy can capture unhandled and deal with them. This concept originated on the Mac, and is particularly useful for implementing something like the "Copy" menu item. The first responder is the target of the "Copy" menu item, meaning that the selected text field gets a chance to handle the copy event first, then its superview, and so on. Further reading: iPhone Application Programming Guide: Event Handling
Application Delegate: This is simply the delegate of the application's UIApplication object. It typically receives general status messages about the application, such as when it starts, ends and what not. It's a good spot to kick off things that need to happen when your app starts or shuts down. Further reading: Cocoa Fundamentals Guide: Delegates and Data Sources
Hope that helps.

Related

Understanding application flow of iOS 7 apps. What happens on launch?

I'm new to Objective-C and iOS programming. I've read through a few of Apple's "Getting Started" docs and I've downloaded a few sample applications to try and get familiar with what is going on in the app. What I'm confused about is what exactly happens from the application's launch. I see in main.m that UIApplicationMain gets called and invokes the AppDelegate. From what I've read, now, if applicationDidFinishLaunching returns true, the app will enter the main event loop.
Is this all correct? If so, how do I tie my code to events? Where do I create instances of my classes when an event occurs?
Finally, from my understanding, Xcode now creates all template apps with storyboards. However, some applications I am looking at are a bit older and don't use storyboards, but I don't see .xib or .nib files anywhere in the directory, but the applications successfully build. Am I wrong in assuming that applications require these files?
An application does not require a .xib or .nib to run. Many programmers do not use any of the visual design tools that generate storyboards or .nib files. You can define your UI completely in code if you wish.
The call to UIApplicationMain in main.m creates a singleton UIApplication object, sets up an event loop, and sets up your UIApplicationDelegate which works in tandem with UIApplication so you can customize the behavior of your app at key points in its lifecycle. UIApplication manages the event loop for you. It receives events from the system and dispatches them to your code for handling.
In order to really understand event handling you need to understand the responder chain. If you look at the superclass of your app delegate you will see it is UIResponder. This is the interface that lets objects respond to and handle events. It is the superclass of UIApplication and UIView and handles most of the raw event handling for you. Events follow a defined path through your code. In the simplest case, touch events, UIApplication pops an event from the event loop and hands it off to UIWindow. UIWindow will perform a hit test to try and deliver it directly to the UIView under the finger. It gets more complicated and motion events take a different path but the point is that much of the raw event processing is handled for you by UIKit. All you really need to do is setup your UIWindow and its rootViewController and events will follow a specific delivery path through all your UIKit responders. You can read about the responder chain in detail here https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html.
When your app starts, the following delegate methods will get called in this order:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions;
- (void)applicationDidBecomeActive:(UIApplication *)application;
In addition, your initial view controller will get created and shown and the following methods will get called (assuming you are using storyboards or xib files):
-(void)viewDidLoad;
-(void) viewWillAppear:(BOOL)animated;
As for "tying your code to events", what type of events are you talking about? What are you trying to accomplish?
You no longer need to use xib files if you are using storyboards, however, you can if you want to.

Should I be writing the majority of my code in a controller or the delegate?

I was using Xcode 4.1 and after upgrading to 4.2, things started to become out of date. I am using many examples from different books, such as Big Nerd Ranch Guides, which do not use Storyboards and the Windows-Based Application had been changed to "Empty" Application.
With these new changes, I feel like the books and tutorials I had been using to start have become outdated. In many of these examples, they say to write the methods and variables in the delegate header files for 4.1. With the new 4.2 Xcode, there is an AppDelegate and ViewController. Should I still be writing the methods and class members in the AppDelegate, or should I be now writing them in the Controller file?
I am confused. Does Apple now want us to create our controller and reference it through the delegate?
When your app is run, it creates an instance of UIApplication. You want to know things that only the UIApplication object knows (did we just get switched to the background? did we just open?) so you use the delegate pattern to get it. When you start a new project Apple starts you off with an already-assigned App Delegate. You can open up MainWindow.nib and inspect your App Delegate to see how it is connected to your UIApplication instance (File's Owner, in this case).
In general you only want to put code in there that has to do with the basic functionality of your app. Launch, quit, go to background and come to foreground are when you'll be doing things in the App Delegate.
Most everything else should go in your view controllers or model objects. Since 'delegate' is just a design pattern, your view controllers can be delegates of other objects. For example, if you present a UITableView, you will assign a view controller as it's delegate in order to respond to events such as selection and scrolling. Your app has many delegates, but it only has one App Delegate.
The AppDelegate is really just a "launcher" for your app. Ie: You shouldn't be writing much code in it at all.
If you're concerned with "set up" code, do it in your View Controller, under viewDidLoad.

Difference between AppDelegate.m and View Controller.m

Could anyone tell me when we use the AppDelegate.m and AppDelegate.h during iPhone programming? I have used only the ViewController.m and ViewController.h for basic learning. I just want to know when and why AppDelegate is used.
Both define classes, but the classes are used for different things. ViewController.h/m define a view controller class that manages a hierarchy of views -- basically, one screen of an application. You might have multiple screens that each have their own view controller.
AppDelegate.h/m define a class that manages the application overall. The app will create one instance of that class and send that object messages that let the delegate influence the app's behavior at well-defined times. For example, -application:didFinishLaunchingWithOptions: is sent when the app has finished launching and is ready to do something interesting. Take a look at the UIApplicationDelegate reference page for a list of messages that the app delegate can implement to modify the behavior of the application.
I would like to add the following to #Caleb's answer.
If care is not taken, the AppDelegate could easily become one of the most accessed objects in the application. I usually refrain from calling methods in the AppDelegate from any of my ViewControllers. Unless, something needs to be reported to the AppDelegate that would influence the behaviour of the whole application.
I keep my AppDelegate for the following:
initialization: whatever needs to be done on the very first launch (after an install or an update)
data migration from version to version (e.g. if you use CoreData and migrations)
configuration of objects linked via IBOutlets from MainWindow.xib
determining the initial orientation to launch in
saving uncommitted data / state prior to the application being terminated or entering background mode
registering for the Apple Push Notification Service and sending the device token to our server
opening one of the supported application URLs (e.g. maps://)
For other use case scenarios and a more thourough description of the AppDelegate, see the iOS Application Programming Guide.
The view-controller. h/m is responsible of controlling the connection between your model and your view (more on MVC here).
AppDelegate. h/m is responsible for the life-cycle of your application. What to do when the user press the home button and exit your app, what to do when the app enter background. Things like this.

Beginner iPhone Development Questions

I have recently started to learn about programming for the iPhone and after going through numerous online tutorials and books (most of which tell you to write this here without offering any explanation as to why or how stuff is working) I still have many questions unanswered and it would be great if someone could help me clarify them.
Here goes:
1) In Interface Builder, what is file's owner, first responder, and a delegate, and where is the actual code that draws the view?
2) When using Interface Builder and you add components to the screen, I understand that Interface Builder doesn't automatically write the code for you, but how should I handle the events fired by the different components? From a best design practice view, should each component have its events handled in a separate file? (would such file be the component's delegate ?) or is it better to just make the viewcontroller class implement all of the interfaces of its components?
3) When creating a UITableView for example, and I define the function:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}
I am saying that the object tableView of type UITableView has this callback function. Right? So in case I have another UITableView named MyTableView I should write a function as such:
- (NSInteger)MyTableView:(UITableView *)MyTableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}
There's some big questions here and very hard to answer in a stack overflow post.
1)
A. What is the File Owner?
The nib is a file right? So what would own the nib file? Well the owner is whatever object you call initFromNib: on.
AClassName *theOwner = [[AClassName alloc] initFromNib:#"nibfile"];
A nib file is just a freeze dried object, a description of an object, a serialization of an object. The object is often freeze dried with a bunch of helper objects to it can be unfrozen and ready to go. Remind me of how Egyptian Pharaohs were buried with many of their servants and many of their possessions, they would be ready to go in the after life. The owner is the main object that has been frozen. In a frozen state (the nib file) the owner is frozen and you can't work with it. When you unfreeze by loading the nib file the main object that's unfrozen is the owner.
B. What is the First Responder?
When you interact with your program by touching the screen, shaking the phone, typing on the keyboard the program must respond to that event, many other frameworks call this handling the events or actions. The First Responder is the first object that gets to respond to the user's interactions. This will typically be the NSView that the user touches, which responds by redrawing itself and sending updated information to the View's Controller (Remember, NSView inherits from NSResponder - now you know why).
It's in the nib file so you can override the typical behavior. The Cocoa Framework is used for the Mac too so programmers might want to have a single object handle keyboard input rather than letting each view handling the keyboard input itself. This is rarely used in iPhone programs directly, because you typically want what the user touches to respond to user interaction (redraw itself) and pass on updates. So you can usually just ignore it in the nib file.
C. What is a Delegate?
What does a person do when they delegate? They tell someone else to do this job for them and report back. People delegate all the time. I delegate fixing my car to a car mechanic. I delegate cooking dinner to the cook at a restaurant I'm dining at. "Johnson, I need you to write that TMI Report for me" said my boss delegating to me for I was company expert on TMI. Classes in the code are no different.
The delegate in the Interface Builder is the Application's delegate. The UIApplication class is going to hand off lots responsibilities to it by sending messages to methods defined in the UIApplicationDelegate Protocol. For instance if your delegate implements the applicationDidFinishLaunching: method it'll receive a message after the instance of UIApplication has initialized and finished its startup routine.
D. Where is the drawing code?
Apple has provided with the Framework in classes like NSView, NSWindow, NSTableView and it's not open-source so you can't view the source code. But the reason the window launches and appears when your first run an application built on one of Apple's templates before adding your own code is due to what occurs in the file main.m.
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
The call UIApplicationMain(argc, argc, nil, nil) starts everything rolling. It loads in the nib file to unfreeze the UIApplication object and other objects in the nib file. Then it asks the application to start it's main loop. Once unfrozen the UIApplication object (the nib's owner) then tells it's MainWindow to display on the iPhone Screen and keeps the UIApplicationDelegate in the loop about what's going on.
Well that's my answer to 1). Took a while to write I hope it helps. One thing that really helped my understanding was: creating a new Window-based Application project, deleting the MainWindow.nib and then attempting to recreate it from an empty nib file, so that it functions the same way.
Here goes:
In Interface Builder:
The "file's owner" is the Objective-C class to which your interface belongs. Usually for a view controller this means the custom view controller subclass you're creating.
The "first responder" is mostly there for behind-the-scenes handling of events; it's used to figure out when your class and interface handle events, and when to pass them up the responder chain.
A "delegate" is a general term for any object which receives messages about the actions of another object. In Interface Builder, it can sometimes be used to pass actions around between objects, or can refer to the "app delegate," which is a class that exists in almost all iOS projects and receives messages about the behavior of the application itself.
To handle events from your GUI components, the generally accepted thing to do is to define a method with return type IBAction in your view controller implementation, then hook it up to an event from a component. Then when that event is triggered, your method is called. It's not usually necessary to break them out into a lot of separate files unless you have a very complex structure.
Not quite. If you have another table view, you can call it myTableView, but you should still hook it up to the same table view delegate and data source, and the method name doesn't change. Let's break the first part of this method signature down:
The (NSInteger) means this method returns an integer
The phrase tableView: is part of the method name, and shouldn't be changed. A table view will always call the method tableView:numberOfRowsInSection: for the information it wants, so changing to `MyTableView* would break.
(UITableView *) means the first argument is of type UITableView
tableView means that the name of the variable inside this method for the calling table view is tableView
Think about reading through the View Controller Programming Guide - it covers a lot of these concepts and links to more documents that explain delegation, table views, etc.
1.) File owner is the (generally) UIViewController subclass associated with the View you are building in IB (what you call GUI builder is actually termed Interface Builder)
First Responder is generally used in the background by the program to indicate what has control at the moment (generally don't do much with this)
The delegate is the file that receives the actions done on the view (and thus must implement how to handle these), (see below)
2.) Generally you will have a ViewController code file for each Interface Builder View (the File Owner). Generally this will be where the actions are handled for specific components (say, clicking on a button). You will set up variables (and methods for button clicks and etc) to handle each component from IB (a textfield or button is an IBOutlet, while an action like clicking on a button is an IBAction) As far as best design, I believe you should have a delegate for each view that does all the above, but I generally just use the ViewController as the delegate and implement it there (for relatively simple views)
3.) No, the parameter name (which is what tableView and MyTableView are in your examples) are used inside the function to indicate the value that you passed it. When you call this function you would call it like [myTableView numberOfRowsInSection:2]; and inside the function anything you needed from "myTableView" is actually referenced by the parameter name tableView...That is for any function, but for UITableViewDelegate methods (like the one you are referencing, it will be called automatically by the UITableViewController if it's delegate is set to the file you define this function.
Wow looking back thats some blocks of text, my best advice would be to get Beginning iPhone Development by Mark and LaMarche, it addresses all this very well.
I'd also suggest looking at some of the very basic examples in the Apple documentation to get a gist for how Interface Builder and delegates are properly used.
Edit: as a commenter pointed out, the Stanford iOS course is fantastic and where i learned the basics (along with the book above)
See my answer to this question for an explanation of what "loading a xib file" means and the meaning of File's Owner and outlets. It's perhaps a bit advanced for a beginner, but if you really want to know the "what" of what's going on and figure out the "why do it this way" for yourself, it's probably a good read:
Put a UIView into a UITableView Header

Quick overview of the structure if iPhone apps

Can someone give me a quick, one-to-few paragraph(s) overview of the structure of iPhone apps. I'm working my way through a book, but I can't really understand the purpose of App Delegates, MainWindow.xib vs. individual views' nib files, actions vs. outlets, etc.
I'm looking for a high-level description, because all I can find are really detailed accounts of this stuff.
You can find out more about Objective-C design patterns like delegation in Apple's documentation. Here's a quick overview of the things you mentioned:
Objects communicate with other options in various ways, one of which is delegation. An app delegate is an object that receives certain messages from the application.
XIB files contain a description of your user interface and connections. MainWindow.xib contains the UI information for your main window, but you should have individual XIB files for other view controllers for the sake of efficiency (you should load the XIBs lazily when the user tries to instantiate a certain kind of view controller, and cache the XIB to prevent reloading it; see UINib for detail).
Actions and outlets are ways of connecting code to UI elements in your XIB. An action is a message sent by a UI element to an object. For example, a button press can send an action to your view controller. An outlet would be a reference to that button.
For more about Objective-C in the context of iOS development, consult the documentation:
http://developer.apple.com/iphone/library/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/index.html
http://developer.apple.com/iphone/library/referencelibrary/GettingStarted/Creating_an_iPhone_App/index.html
The physical structure of an iPhone application consists of a directory that acts as a bundle for the main executable and all resources used (images, property lists, interface files, etc.).
When run, the executable first performs the main() function. That function either programmatically instantiates an application delegate or loads the main interface file (which specifies the application delegate). The application delegate acts in response to application-level events, such as termination or entering and exiting the background.
The construction of your interface can either occur programmatically or through the use of Interface Builder .xib files. If programmatically, your application delegate will construct the initial overall interface, then hand things off to individual view controllers to manage the display of specific views. If done via Interface Builder, you'll define interface files that compile into freeze-dried objects that are deserialized into your interface at runtime.
Overall, Cocoa applications tend to follow the Model-View-Controller design pattern, where these three areas of your application are separated in code. Views are generic reusable display elements, your model contains application data (often persisted using Core Data or SQLite), and your controllers provide the application-specific logic that glues everything together.