understanding methods in objective-c - iphone

for example we use this method in the tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 16;
}
i want to learn we don't call this method in anywhere but application reads this value how is it being? there are a lot of methods like this we did not call.

Your object has been set as the data source of the UITableView somewhere. Most likely, by making a connection in InterfaceBuilder, though it is straightforward to do so in code by setting the dataSource property of the UITableView:
- (void) setUpMyJunkMan
{
myTableView.dataSource = self;
}
Once you have set your object as the data source, the table view will invoke the method as needed to determine what it needs to draw or how it needs to respond to events.
Your object is required to implement the UITableViewDataSource protocol (though, if you connected the data source via InterfaceBuilder, there may not be a complaint if you don't -- it is more of a compile time validation than a runtime one).
If you look at the declaration of UITableViewDataSource, you'll see that a number of methods are #optional. The rest are #required; you must implement them to fulfill the contract of the protocol.
This is the key difference between data sources and delegates. Delegates can optionally implement any of the declared methods. Data sources create a much more formal relationship between the two objects wherein some of the methods must be implemented.

An easy way see why a method is being called - set a breakpoint, run in debug mode, and then look at the stack trace.
For this particular case - It's being called automatically by the framework when it renders the table view.
I think you really need to take a look at The Table View Programming Guide so that you have a good understanding of what methods you need to override (and not override) when using Table Views. If you are extending the TableViewController class the framework does a lot of the heavy lifting and you barely have to write any code.

numberOfSectionsInTableView: is being called by the table view.
You implement numberOfSectionsInTableView: as part of the UITableViewDataSource protocol. Each UITableView is given a dataSource. Normally, UITableView will be constructed by a UITableViewController which will set itself as the view's dataSource.
When the view is shown, it calls numberOfSectionsInTableView: on its dataSource.
This is explained in the Table View Programming Guide for iPhone OS.

This is part of a Delegate Interface.
At some point in your application (possibly in your UIBuilder) you have specified that the object that contains the method is actually the delegated object. This means that when you want to adjust the behaviour (in this case of a UITableView) you can without actually extending UITableView but mearly changing the delegate methods.
basically the UITableView class will look somehting like this.
- (void) AMethodinUiTableView
{
int colums =[self.delegate numberOfSectionsInTableView:self];
}
for more info i would check out delgate programing and selectors.

Related

Understanding what happens and why you need a delegate and source for table views

I have been practicing with table views and I know how to create them but I would like to have a better understanding about delegate and source when creating table views.
Can someone explain the need for a delegate and a source when creating table views?
Why do you need them?
What is happening when you connect delegate and source to File’s Owner or ViewController and why they need to be connected?
I guess I need a general explanation about delegates and source and what happens when you connect them to File’s Owner or ViewController?
The delegate and data sources allow the tableview to conform to the MVC design pattern, which is a recurring design pattern in Cocoa and Cocoa Touch.
The TableView itself provides the [V]iew part and the delegate provides the [C]ontroller part while the data source provides the [M]odel part.
When you connect the delegate and datasource in the NIB file you are creating this connection visually; you can just as easily do it programmatically.
Delegate:-
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object—that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit—that is responding to a user event. The delegate is an object that is delegated control of the user interface for that event, or is at least asked to interpret the event in an application-specific manner.
Data Source:-
A data source is like a delegate except that, instead of being delegated control of the user interface, it is delegated control of data. A data source is an outlet held by NSView and UIView objects such as table views and outline views that require a source from which to populate their rows of visible data. The data source for a view is usually the same object that acts as its delegate, but it can be any object. As with the delegate, the data source must implement one or more methods of an informal protocol to supply the view with the data it needs and, in more advanced implementations, to handle data that users directly edit in such views.
For Detail info goto
http://developer.apple.com/library/ios/#documentation/general/conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html
You dont need to make any connections if you are happy to write the following code:
tableview.delegate=self;
tableview.dataSource=self;
The UITableViewDataSource protocol is adopted by an object that mediates the application’s data model for a UITableView object. The data source provides the table-view object with the information it needs to construct and modify a table view.
Example:
Whereas a data source type object gives data to another object. For example again, the UITableViewDataSource protocol has methods such as cellForRowAtIndexPath and numberOfRowsInSection dictating what should be displayed in the table
The UITableViewDelegate of a UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.
Example :
A delegate type object responds to actions that another object takes. For example, the UITableViewDelegate protocol has methods such as didSelectRowAtIndexPath for performing actions upon a user selecting a particular row in a table.
If your programming language doesn't support multiple inheritance, you must use delegate method. When you implement delegate method, you can use object functions such as super class. Example :
// define tableview row count
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
// define tableview height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
}
// define specific tableview cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = MyCell();
return cell;
}

What exactly does delegate do in xcode ios project?

I have just been learning iPhone apps development but I have a hard time in understanding what delegate actually means? Can anyone tell me with example what it does and how important it is? Thanks for any helps!
It's a key concept to understand conceptually so getting your head around how to think about it ahead of the technical details is important. Simply put, a delegate is a callback.
Two main scenarios to use delegates:
A class or control wants to abstract out the details on how to do work (like retrieve data).
Allow others to hook code into a pipeline.
Examples:
UITableView - a table view is just a control that knows how to render a list of cells. It handles all the heavy lifting of rendering, scrolling, etc... But, it has no idea how to load your data. So you implement a datasource delegate which has methods to get the cell data for a given row etc... That makes it easy on you. You just use the control and plug in the specifics for your data. The UITableView will do everything for you ... just answer a few specific questions for. A delegate answers those few specific questions.
A text control - you add a text control to your view and voila! you can type in it and alls good. But what if you want to do something when they start typing or when they're done typing? Well, the text control offers a delegate with methods that allow you to hook into the execution pipeline of the text control. It allows the text control to do everything for you and allows you to interject code where you need it. Many times, there's way to interject code to make a decision on whether something is allowed. The control will call back and ask, should I be able to do x? You can interject code and influence the behavior.
If you're creating a control or class, you can create your own protocol, datasource delegates etc... so your control can focus on doing what's advertised. For example, let's say you wanted to create a task control. You could:
First, create a contract. Hey, if you're going to provide data for my control, these are the questions I'm going to ask you. I'll take it from there... In this case, I'm going to ask you the number of tasks and I'm going to have you give me a task given the row number.
#protocol XXTaskBoardDelegate <NSObject>
-(NSInteger*)getTaskCount;
-(XXTask*)getTaskForRow:(NSInteger*)rowNumber;
#end
In the control or class, give the consumer a way to give us the delegate datasource class that will answer the questions the control will ask. At this point, the control is a pure control. It knows nothing about how you get your data. It's asking for an object (id) that implements a contract/protocol. id
#implementation XXTaskBoard
- (void)setDelegate:(id<XXTaskBoardDelegate>)newDelegate
{
// the control stores the delegate so it can callback and ask you questions.
}
Then, for the delegate class, in the header declare you implement that formal protocol
and in the implementation m file you provide the code.
#interface AppController : NSObject<XXTaskBoardDelegate>
{
//...
}
then, implement it in the implementation
#implementation AppController
- (NSInteger*)getTaskCount
{
return [model queryTaskCount];
}
- (XXTask*)getTaskForRow:(NSInteger*)rowNumber
{
return [[model tasks] getItem:(NSInteger*)rowNumber];
}
A delegate is an object that another class can pass messages to. In practice delegate classes have to conform to a delegate protocol.
For instance we will take a subclass of a table view controller. This is a delegate for your table view. First you define that it is a table view delegate by doing this:
MyTableViewController : UITableViewController <UITableViewDelegate>
This says that class MyTableViewController is a subclass of UITableViewController and CONFORMS to the UITableViewDelegate protocol.
Setting [tableView setDelegate:self] (or defining it as such in IB) then passes the self object to the tableview in order for the tableview to send messages to it.
The main message it sends is the didSelectRowAtIndexPath message which tells your class that the user has pressed a table view cell.
So the object that takes the click event (the table view) passes on the message that the cell has been clicked to the delegate object (which in this case is your MyTableViewController object).
Delegate protocols exist so that you can make sure that the delegate object has the necessary methods to deal with your messages. Methods in a delegate protocol can be #optional or enforced. Any methods that are optional don't have to be defined. In your MyTableViewController class the method didSelectRowAtIndexPath is optional - you don't have to have it. If the table view doesn't find the method it just won't call it.
However the cellForRowAtIndexPath is necessary and without it your app won't compile.
I hope this helps and is straightforwards for you. If you need any more info let me know.
Delegates are just way of getting callbacks from something. You pass a delegate (a pointer to an object that conforms to a protocol) to something and when it has new data for you or when an event occurs that something make a method call on the delegate.
For example, when events occur, like your app is put into the background or the app is about to terminate the UIApplication object will call your application delegate to let it know. When a CLLocationManager has a new GPS position is will call your delegate to pass it the new position. UITableViews call their delegates to get UITableViewCells to display in the table. There are many uses of delegates in iOS.

Problem understanding Delegating pattern & callback functions in Objective C

Can anyone simply explain delegating pattern and callback function in objective C.
Or can point to some documents (with Easy and Basic Explanation) which can make these concepts clearer to me. As i am not getting any idea about it from any book or website or (Apple Developer)references.
All the resources i have come across to understand this, makes me more confuse by using the terminology which i find hard to digest.
Any Help Appreciated.
I will try to explain the value of delegation with one example.
Say you have a table; the table will show some rows. Suppose now, you want to customize the way this table react to some event, e.g., the selection of a specific row.
One common way of doing this in OOP is subclassing a table base class and overriding some methods there.
With delegation, you don't need subclassing the table base class; rather you use the base class and tell it to "forward" some messages to some other object. This is the basic idea.
In our example, when the row is clicked, the table base class does not know what do except sending a message to one object that you specify as the delegate to carry through that action.
So, one basic advantage of delegation is that you do not need to subclass. Another advantage you have is that a delegate can act as the delegate for several other objects. Indeed, if you have a look at the generic declaration of a delegate method, you will see that the first parameter is the object that is delegating:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
so when the delegate receives the message, it knows who sent it and with which object it should interact.
The example I gave you about the table shows one kind of delegation, which I would not compare to callbacks. Anyway, delegation can be used as well as a kind of advanced calling-back-scheme.
Take the class NSURLConnection; it can be used to manage aynchronous communication.
Async communication is the typical case where callbacks are used.
With NSURLConnection, the delegate pattern is preferred; so, instead of specifying a callback (a function, which has to be a static function, or a static class method), you specify an object. This object implements the methods that a protocol defines (NSURLConnectionDelegate protocol); you can see those as a whole set of callback functions. When the NSURLConnection has some data ready, it will call a method of the interface, e.g., – connection:didReceiveResponse: to notify that it has received the response.
In such case, the point is not avoiding subclassing, rather it is a more flexible callback mechanisms (allowing for better encapsulation, basically).
I hope this helps clarifying the two concepts...
delegate noun |ˈdeligit|
A person sent or authorized to represent others, in particular an
elected representative sent to a conference.
A delegate in the Cocoa Touch frameworks such as Foundation or UIKit is a separate object instance that is entrusted to listen in to, and optionally decide behaviours on behalf of the delegator.
Take the example of UIWebView. The web view can entrust responsibility onto one delegate as long as that instance conforms to the UIWebViewDelegate protocol, that is promises to behave as the web view expects a delegate to behave.
The delegate gets called from time to time. Embedded in the delegate method names is information about what the call is about.
webView:shouldStartLoadWithRequest:navigationType: - Tells the delegate that the webview wants to load a request, and ask the delegate if it should do so.
webView:willStartLoad: - Tells the delegate that the web view will start loading a page, and it is too late to do anything (This is a hypothetical method that is not actually available, I use it as a consistent example).
webView:didFinishLoad: - Tells the delegate that the web view did load a page and it is now finished.
The value of using delegation is that you do not need to sub-class UIWebView in order to tweak how it behaves. One objkect can also serve as delegate to many different webviews, or even serve as delegate to many different kinds of classes.
A normal UIViewController subclass probably conforms to many delegate protocols, for example UITableViewDelegate to respond to selections in a table, UIActionSheetDelegate to respond to selection from an action sheet, etc.
In Objective-C they make a big deal about delegates and make it seem like they're somehow special, but they're simply objects that get called. The only difference is the way they're used: You pass a class instance pointer to some service, and it calls back through specified methods of that instance when it needs some action or data from your code (very much similar to the callback scheme used in other languages).
"Protocols" are just a way to define the methods used in a delegate arrangement. It's a "poor man's multiple inheritance" scheme, virtually identical to the "interface" concept in Java.
But because "protocols" are available, you can (but don't have to) make your delegate class the same class as, say, your view controller. This simplifies your design in many cases (data can be easily shared, etc), but it's not at all mandatory to "share" a class that way, vs using a unique class for the delegate.

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

iPhone Programming - How do I programmatically make a view that requires two delegates?

Here is my dilemma. I would like to have a text box and a button. The user types in text and then presses the button. Once the button is pressed, a text message window (using MFMessageComposeViewController) comes up. I don't know how to set this up. The problem is that the TextBox will require a delegate (UITextFieldDelegate) and the MFMessageComposeViewController will require an MFMessageComposeViewControllerDelegate. How can I have a .h file that declares a view that is more than one delegate?
I'm new to iPhone programming so any help on how to have an interface view that handles more than one delegate (so that I can have multiple types of controls in my view) would be really helpful!
A delegate does not need to be a view. Indeed, in most cases it probably shouldn't be. Often you will make a controller object the delegate, although this depends a lot on what you're doing.
The delegate protocols you need (MFMessageComposeViewControllerDelegate and UITextFieldDelegate) are quite distinct, so a single object can readily implement the methods of both without any confusion. But even if you are the same delegate type for several objects, the methods will be passed a pointer to the calling object so you can decide what to do case-by-case if necessary.
If you just mean how do you declare your class as implementing both protocols, you would do this:
#interface MyDelegate : NSObject <MFMessageComposeViewControllerDelegate, UITextFieldDelegate>
{
...
}
...although this presupposes that the protocols are formally required, which I don't think is the case here. In which case such a protocol list is unnecessary.
Otherwise, I probably am not understanding your question...
EDIT: OK, it seems like what you're looking for is how to link up the delegates at runtime. This varies according to the particular class, but for MFMessageComposeViewController you do this:
MFMessageComposeViewController* composer = ...;
id<MFMessageComposeViewControllerDelegate>* delegate = ...;
composer.messageComposeDelegate = delegate;
Easy, no? In this case the protocol is required, so you'd have to include it in the interface as described previously.
In general, if an object uses a delegate for anything, it will have a property or a method to allow you to set it, which you'll find in the documentation. Eg, in this case: Properties for MFMessageComposeViewController.
Note that delegate properties are conventionally weak references, so the objects in question need to be retained somewhere in your application.