Specifics of implementing custom delegate methods - iphone

I want to use my own delegate methods. i follow the tutorial .but is it must to use the class in which i have declared delegate method(protocol definition) for calling that delegate method?cant i call without creating the object for the class in which i have protocol definition? what is the use of the method "delegate respondsToSelector:#selector"…?any help pls.?

what is the use of the method
"delegate
respondsToSelector:#selector"…?
In objective-c you can send any message to any object, BUT if object can't respond to it then your program may crash - so if you're not sure if certain object responds to some selector then you can (and should) check that in run-time using respondsToSelector: method - it can save you from a lot of troubles.
You don't have to declare protocols as well but they are a good way to make sure that objects of some type respond to selector in compile-time.

Also see Apple's Communicating with Objects, which discusses delegates, protocols, and selectors. Though its listed under Mac OS X, most (if not all) appears to apply to iOS also.

Related

In Swift, does an object conforming to a protocol absolutely need a delegate variable in order to work with the protocol?

I'm working through another UITableView tutorial and it always my learning process always reverts back to the idea of protocols and delegates. The area that is a bit confusing is the idea of a delegate variable of that type protocol. It seems that when programming, if you choose to make an object conform to a protocol then it appears that you need to create a variable called delegate as well (of the type protocol)? Part of me says this isn't true that we have to create this variable but I'm not sure plus I'm not fully understanding the reason for this variable.
I comprehend that in order for an object to conform to a protocol then it needs to implement certain variables and/or methods. I always get confused when I see a tutorial that creates a variable called delegate within the same object. If the object already conforms to the protocol by implementing the variables and/or methods, then what is the reason for creating a variable called delegate and setting the type to that of the protocol?
If the object already conforms to the protocol by implementing the variables and/or methods, then what is the reason for creating a variable called delegate and setting the type to that of the protocol?
The whole purpose of the protocol in the protocol-delegate pattern is that the only thing this class, which is going to be sending delegate messages to the delegate, needs to know or care about, is that the delegate is an adopter of that protocol — i.e., that it implements the variables / methods. This class doesn't need to know the actual class of the delegate; it just needs to know that that the delegate can be sent the delegate messages.
Thus, it's all about the compiler. The object acting as delegate may conform to the protocol, but the compiler doesn't know that unless this variable is typed as a protocol-adopter. And if the compiler doesn't know, it won't let us send delegate messages to the delegate object! So that's how we type it. That's the minimum the compiler needs to know in order to allow us to send the delegate messages.
No, protocols are a separate concept from delegates. The delegation pattern in Cocoa generally uses a protocol, though it doesn't have to. Before ObjC 2, almost all delegation was done with "informal" protocols (i.e. there was no actual protocol defined). In Core Foundation and Swift, delegation can be implemented with structs rather than protocols (this is somewhat common in Core Foundation, but more rare in Swift today).
There is a tradition in Cocoa of using a property called delegate which you use for the delegation pattern (also called the "Strategy Pattern" in some languages). It is an object that tells you how to behave (you "delegate" decisions to it). Cocoa has a long history of consistently naming things, and using the name delegate is very helpful because it also implies to the reader that it's a weak reference (again, by tradition). Sometimes there is also a "data source" which is exactly the same as a delegate, but provides data rather than behavior and configuration.
But protocols are much bigger than this. A protocol is just a promise to implement methods. It can be used for many things beyond just delegation.

Why not subclass UIApplication? Why use a delegate?

Instead of using an application delegate so that the UIApplication singleton can call the delegate methods at predefined time, what are the advantages and disadvantages of just subclassing UIApplication? (update: why does the iOS architecture use the application delegate instead of letting people write an application by subclassing UIApplication and overriding its various methods?)
That's because when we create a new UIView control, we subclass UIView (update: or we subclass UIViewController too). So why for the case of application, we don't subclass UIApplication but use delegation instead?
Again, from the documentation:
Subclassing Notes
You might decide to subclass UIApplication to override sendEvent: or
sendAction:to:from:forEvent: to implement custom event and action
dispatching. However, there is rarely a valid need to extend this
class; the application delegate (UIApplicationDelegate is sufficient
for most occasions. If you do subclass UIApplication, be very sure of
what you are trying to accomplish with the subclass.
From the UIApplication Class Reference:
The UIApplication class provides a centralized point of control and coordination for applications running on iOS.
Every application must have exactly one instance of UIApplication (or a subclass of UIApplication). When an application is launched, the UIApplicationMain function is called; among its other tasks, this function creates a singleton UIApplication object. Thereafter you can access this object by invoking the sharedApplication class method.
So what do you mean by "why don't we subclass UIApplication? Apple even provides notes on what to implement in subclasses.
As for your question about delegation and singleton use over just standard classes, the answer is simple: An application must provide one common way to recieve and dispatch events (both external and system related), handle multitasking, and interface loosely with the system (that's why main.m includes a reference to your app delegate).
The reason developers usually don't is because there is no need to. UIApplication works as it needs to for the majority of cases. It just needs some hints on what to do in certain predefined cases (which is why it has a delegate). UIView, on the other hand, is very generic and I don't think it is ever used as-is. It is probably the most customized class in all of the iOS world.
Delegation is a core design pattern. It allows for the seperation of responsibilities between parts of your program. The idea is that the part of your program that, for example, draws to the screen probably shouldn't be talking to your database. There are several reasons for this:
Performance: if the same object that draws to the screen access your data store, you're going to run into performance problems. Period. Full stop.
Code maintanence: it's easier to conceptualize code that is properly modularized. (For me, anyway)
Flexibility: If you subclass in your code, that's great - until you start running into monolithic classes that have all sorts of undesired behavior. You'll reach the point where you have to overload behaviors to turn things off, and your property namespace can become polluted. Try categories, delegatation, and blocks for alternatives.
That said, I did indeed run into a situation where subclassing was appropriate. I have a kiosk app in which I wanted to automatically dismiss a certain settings menu if it wasn't interacted with for a period of time. To do so, I had to have access to touch events throughout the entire app. I subclassed UIApplication and overrode sendEvent:. That was appropriate then, although it's an edge case. As king Solomon says in Ecclesiastes, paraphrased: There's a time and place for everything under the sun.
To make it easier to write, read, iterate upon, and maintain your program, it is strongly advised that you follow certain practices. You're welcome to subclass many classes, and Apple won't reject your app for poor code, provided that it runs as advertised. That said, if you don't abide by specific tried and true practices, you're digging your own grave. Subclassing isn't inherently bad, but categories, protocols, and blocks are so fascinating, that I'd prefer them anyway.
There are many specialized things that a UIView subclass might need to do. Think of UIScrollView, UIImageView, UIWebView, etc., and how drastically different their internal workings must be. But still, they must participate in the view hierarchy and so subclassing makes sense.
UIApplication, on the other hand, is a central hub for application-wide events, notifications, opening URLs, accessing windows, and other generic things. Under normal circumstances, an app should really just need to know things that UIApplicationDelegate Protocol will provide.
A note from the UIApplication Overview explains one reason that you might subclass UIApplication:
You might decide to subclass UIApplication to override sendEvent: or sendAction:to:from:forEvent: to implement custom event and action dispatching. However, there is rarely a valid need to extend this class; the application delegate (UIApplicationDelegate is sufficient for most occasions. If you do subclass UIApplication, be very sure of what you are trying to accomplish with the subclass.
But this should only be necessary in very special cases.
I'll add something no one else mentioned: Delegation removes the need to call super when overriding/augmenting/adding behavior via a delegate method implementation rather than a subclass with an overridden method. I've seen many developers answer their own Stackoverflow question with simply they forgot to call super (after some have even posted possible answers). The newer method decorator NS_REQUIRES_SUPER helps a bit with this by alerting the developer with a warning (hopefully they don't ignore it!) however it doesn't help when the order of the call to super matters. I think Apple decided it was less error-prone to have developers implement a delegate object instead, that has no calling super requirements, and they even did the hard work of forwarding the UIResponder methods from UIApplication on to the delegate object too.

UITextView with multiple delegates?

I have a UITextView that points to the File's Owner as its delegate, and I have a number of the delegate functions implemented. However, I would also like to point to a second object (in this case a TextExpander object, http://www.freshblocks.com/tutorials/how-to-add-textexpander-touch-sdk-to-iphone-apps/) also as a delegate. How might this be possible? As far as I know there can only be one delegate in objective-c.
I don't know the specific of TextExpander but he delegate design pattern assumes one and only one delegate. You can't have two delegates for one object.
There are ways around this. You could designate one of the delegates as the primary delegate and implement all the methods in this class. That class could then simple call the secondary delegate for the required methods. This is the simplest approach but does result in the primary delegate becoming tightly coupled with the secondary delegate.
Another approach would be to resolve the messages dynamically and use message forwarding. You would still require the a primary/secondary delegate pattern, but instead of the primary delegate needing to implement all the methods it would simply pass all messages it doesn't respond to onto the secondary delegate. This approach means that the secondary delegate can change by adding/removing additional delegate methods without having to change the primary delegate. The key method is - (id)forwardingTargetForSelector:(SEL)sel. See Objective-C Message Forwarding for a good explanation.
It seems that they solve this in step 5, by setting [textExpander setNextDelegate:self]; before setting the textExpander object as the "primary" delegate of the view.
I don't have the code myself so I haven't tried it, though, and their documentation is... well not.
Just for information: Delegates are not an Objective-C feature, but a design pattern using though Cocoa/Cocoa-touch.
Delegate pattern allow only one object to be notified of the changes of another. The solution to have an intermediate delegate object could be an easy way of doing things.
If you want to keep your code clean and reduce the coupling you might use another pattern known as KVO (Key Value Observing). Apple provides a good guide on how to use it.
In KVO a single object, that needs to be KVC (Key Value Coding) compliant, can notify multiple objects without even knowing about it. It uses an intermediate notifier object (singleton for you application).
Check the Apple doc on KVC + KVO and you shall be able to do what you want.
I have a class with the protocol NSXMLParserDelegate implemented. I call this ParserHelper. I parse a lot of XML which happen to have some tags in all of them and i have about 20 parsers (one for each type of XML), and i didnt want to implement it over and over again.
So, I subclassed my ParserHelper class 20 times, adding in each subclass the required tags/behaviours like CaseAParser, CaseBParser and so on...
I just implement the delegate methods i needed and called it on the superclass once i'm done with the method.
I assume it works on every delegate.
This way, all you need is to make your class a subclass of SMTEDelegateController and implement the methods you need, remembering to call the [super whatEverMethod:andParameters] at the end of your functions and you should be good to go.

What are AppDelegates in Objective-C?

I'm working through an iPhone tutorial (link text and it has me put in some code (a few times throughout the various tutorials) but it doesn't explain it at all.
In this code:
todoAppDelegate *appDelegate = (todoAppDelegate *)[[UIApplication sharedApplication] delegate];
What exactly is an appDelegate? What does the "delegate" at the end of the instantiation mean? Actually, what does the whole thing mean? (UIIapplication sharedApplication)?
I am a .Net programmer if that helps someone explain it better. I hate learning through tutorials because I always need to know what EVERYTHING does and no one explains everything.
Let's back up a little bit.
The square brackets ([ ]) are Objective-C's method calling syntax. So if Cocoa had a C# syntax, the equivalent syntax would be:
TodoAppDelegate appDelegate = UIApplication.sharedApplication.delegate;
In C#, you would use a static class for a class that only has a single instance. In Cocoa, the Singleton pattern is used to accomplish this. A class method (in this case, sharedApplication) is used to retrieve the single instance of that class.
Delegates in Cocoa are not like the delegate keyword in C#, so don't be confused by that. In C#, you use the delegate keyword to reference a method. The delegate pattern in Cocoa is provided as an alternative to subclassing.
Many objects allow you to specify another object as a delegate. Delegates implement methods that those objects will call to notify them of certain events. In this case, UIApplication is the class that represents the current running application (similar to System.Windows.Forms.Application, for example). It sends messages to its delegate when things that affect the application happen (e.g. when the application launches, quits, gains or loses focus, and so on.)
Another Objective-C concept is the protocol. It is similar in principle to a .NET interface, except that methods can be marked as #optional, meaning they classes are not required to implement the methods marked that way. Delegates in the iPhone SDK are simply objects that conform to a specific protocol. In the case of UIApplication, the protocol delegates must conform to is UIApplicationDelegate.
Because it's not required to implement every method, this gives the delegate flexibility to decide which methods are worth implementing. If you wanted to, for example, perform some actions when the application finishes launching, you can implement a class that conforms to the UIApplicationDelegate protocol, set it as the UIApplication instance's delegate, and then implement applicationDidFinishLaunching:.
UIApplication will determine if its delegate implements this method when the application finishes launching and, if it does, call that method. This gives you a chance to respond to this event without having to subclass UIApplication.
In iPhone applications, developers also frequently use the app delegate as a kind of top-level object. Since you don't usually subclass UIApplication, most developers keep their global application data in the app delegate.
A delegate is just an object that implements certain methods (basically callbacks). The NSApplication docs explain what its delegate is supposed to do and what messages it needs to respond to to.
And this isn't instantiation. The snippet you posted above doesn't create anything. It accesses whatever object is set as the application's delegate. [UIApplication sharedApplication] gets the object representing the application, and sending delegate to the application gets its delegate (if any).
to add more to the mix of responses and another point of view, delegates are objects that can (but don't necessarily need to) do work for another object.
So let's say you have objectA, and can assign to it a delegate (let's call it delegateObject).
From objectA's point of view, there are certain bits of work that may need to be done. Depending on the context, the actual work and the results of such work can be different.
So instead of having objectA implementing a method for all these instances, we'll say... let's have another object, delegateObject, do the work... and as long as the results are returned in the proper format, we don't care what delegateObject did to get there.
objectA will first check that delegateObject exists and that delegateObject has implemented a method to do the work asked of it.
To accomplish this, NSObject (which every Cocoa object inherits from) has this method:
- (BOOL)respondsToSelector:(SEL)aSelector
and objectA would do a simple test before sending a message to delegateObject, for example:
if ([delegate respondsToSelector: #selector(someMethod:sender:)])
{
[delegate someMethod:#"stuff" sender:self];
}
and because objectA only sends a message to its delegate if one's been assigned, delegate is not retained by objectA.
if we were to use UITableView as an example, it has a lot of UITableViewDelegate methods. One of them is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
every time the user touches a row in a table, the UITableView object will first check that there's a delegate, if there's a delegate, it'll then check that the delegate has implemented the above method. If it does, then it'll send the message to the delegate. This method expects no return value, and UITableView will go about its merry way, regardless of what the delegate does. And if there is no delegate that implements that method, then nothing happens.

Does it make sense that there may be more than one class that conforms to the UIApplicationDelegate protocol in an iPhone App?

I think I've understood what that Delegate is supposed to do. If a class conforms to that protocol, it tells the underlying system: "Hey man, I am the UIApplication object's delegate! Tell me what's up, and I may tell you what to do!".
What, if multiple classes implement that? Is that possible? Does that make any sense?
While you could implement multiple classes that conform to the UIApplicationDelegate protocol only one, the first, would receive these messages.
Implementing a protocol to create a delegate is only one part of the equation. That delegate then has to be registered with the code that's generating the messages and these systems generally only support one delegate.
In the case of UIApplication you can change the delegate using the 'delegate' property in the UIApplication shared class but this will replace the original delegate, not add an additional one.
If you need to broadcast UIApplication level messages to other systems then this is functionality you should add to your existing delegate.
You can implement multiple classes that adopt the UIApplicationDelegate protocol, but only one can be the actual delegate at any given time. It's set by [UIApplication sharedApplication].delegate, which is normally set up by the main NIB file by an outlet connection.
Just conforming to the protocol doesn't set your object as the delegate, you need to do that explicitly either in the nib or in code. As already mentioned, only one object can be a delegate at one time. Having multiple delegates may make sense in some cases-- for example if you have a table view that displays two sets of data, you could make two delegate and datasource objects for it, and switch between them as needed. It probably doesn't make sense to do this for the application's delegate though, since the code there is pretty specific.
Keep in mind that sometimes an object will send notifications in addition to calling delegate methods. A lot of time it looks like they're the same thing, since the object will automatically subscribe your delegate to the notification if it includes a certain method signature. The key difference though is that other objects besides the delegate can also subscribe to these notifications, so you can hook them up to multiple objects at once.
As Daniel Dickson stated:
You can implement multiple classes that adopt the UIApplicationDelegate protocol, but only one can be the actual delegate at any given time. It's set by [UIApplication sharedApplication].delegate, which is normally set up by the main NIB file by an outlet connection.
... but know that you can swap these out at runtime if you need to. I recently looked at using this technique as a way of merging two applications developed by different parties that could not share source code or refactor; yet needed to co-locate under a single icon on the device.