Hey guys, I currently have a root table view which has a toolbar at the bottom and has labels and a refresh button within it, much like the Mail app’s toolbar. This root table view controller obtains data from a server by allocating and initializing a DataUpdater class. Within this class are the NSURLConnection delegate methods that are called while communicating with the server.
As you can probably guess, I need to know when certain (delegate) functions are called within the DataUpdater class and the values of the parameters passed to these delegate functions so that I can update the labels on the toolbar accordingly (i.e. Connecting…, Updated, etc).
The problem I am having is determining how to notify the root table view controller of what is going on in these delegate methods. Would I use protocols, if so how? I have been skimming the documentation and don’t quite see how I would get this effect. Or would you suggest I implement my program another way?
Thanks in advance!
A protocol is a kind of contract that says: I promise to provide the non-optional methods defined in the protocol, and maybe even the optional ones. It’s purpose is like Java interfaces: to work around missing multiple-inheritence.
The delegate pattern in Objective-C normally works like this: you define a protocol, and then in your class, you define a variable like
id<MyProtocol> myDelegate;and define a setter and maybe getter (either via normal methods, e.g.- (void)setDelegate:(id<MyProtocol>)aDelegate;or via properties.Note that the delegate is not retained ! So if you work with a property, you need the
assignoption, notretain.Now back in your class, you check whether
myDelegateis nil and if not, you can directly call its non-optional methods. If you want to call an optional method, you first need to verify its presence viarespondsToSelector:.So if you decide to use the delegate pattern, you need to define a protocol, add that protocol to your root table view controller, implement the necessary methods there, and make sure to call
[foo setDelegate:self];or something similar to inform your other class that the root table view controller is the delegate. And of course implement the delegate calls in your class.Edit:
An alternative might be to use
NSNotifications, BTW. The advantage of notifications is that you can have multiple objects listen and react to them. The disadvantage is that you cannot (directly) pass values back. For example, you can define a delegate method that asks the delegate whether to do something or not. That’s not possible with notifications, it’s more like shouting into a room instead of having a one-to-one conversation.