iOS but why delegate - ios

I see everywhere in iOS programming that delegate is used....I am not sure what for is being used.
Can you please explain me about it?

When you need objects to behave differently from each other, you can either give them different implementations (often by subclassing, as is done with UIViewController), or by delegation. The difference is that polymorphism in the first case is achieved by making the objects of different type, whereas in the second, polymorphism is achieved by making objects of the same type delegate certain bits of functionality to objects of arbitrary type.
The reason people like delegation so much is that it allows a much cleaner class hierarchy: you don't need to subclass every little thing, just to respond to a few hooks. That's why we use delegation.
If you want to know the mechanics of delegation, and how to do it in your own classes, you're welcome to see my article Using custom delegates in Objective-C.

It's all just about optional function calls.
Objects can designed to optionally call methods in other objects. Some of those optional methods can be grouped together into a delegation pattern.
A delegate is simply another object that wants to be called by those methods. When you set a delegate, you let the calling object know that somebody wants to be called (accept the option), and who to call (the "delegate") whenever the option comes around.
If nobody wants to be the delegate, then the calling object with the option will usually just do some default behavior. So this pattern ("delegation") is a good way to be able to modify defaults, but not have to do so, and without requiring creating a lot of subclasses (which can get more confusing more quickly in the opinion of some people).
Here's another Stack Overflow answer about Delegates, I gave awhile back.
See Apple's Documentation on these design patterns.

Related

Why do delegates exist in iOS?

I understand that delegates are essentially objects that another object can pass messages to, and that they are used on behalf of other classes. So for example, a UITableViewDelegate has methods which can be used to detect particular events in a UITableView. This is very useful, and indeed I have used delegates a lot in past iOS projects, so this is more of a curiosity:
Why do the methods in a delegate class not just exist in the class that the delegate is being delegated by?
Surely it would be more convenient to have those methods in the actual class, such as a UITableView?
Perhaps it is that architecturally it is more convenient, but from fist looks it seems counter intuitive.
As a general rule, composition is more powerful than inheritance. Inheritance creates many subtle problems, the most common of which is the diamond problem, but there are many other problems.
Delegation is just a specific formulation of the Strategy pattern, which allows us to extend an object via composition rather than inheritance.
As a concrete example of the issue, and how the diamond problem creeps in when you use inheritance, consider this:
You have a very common way you want to provide cells. For example, you'd like a Core Data fetch request, or a network request that generates cells. So you would build a superclass that encapsulated all this logic. We'll call the class that handles thatFetchRequestDataProviding.
Separately, you have a visual behavior you use a lot. For example, you want a particular kind of animations for your view, so you wrap that up into a class FadeInTableView.
Now we have a problem because we want both. So we need multiple inheritance. And multiple inheritance is Pandora's box of ambiguities.
But I eliminate all of that if I make FetchRequestDataProviding a separate object that behaves as a delegate. I actually could make things even more powerful by breaking out FadeInAnimating as a delegate/strategy (though UIView doesn't have that power today).
In ObjC, "composition is more powerful than inheritance" shows itself commonly in a fairly shallow inheritance tree and lots of delegates. Swift pushes this further with protocols and structs that have no inheritance. None of this means that inheritance is bad; it can have a lot of value (though languages like Go avoid it entirely; though interestingly still has to face the diamond problem due to embedding). But when in doubt, composition is the more powerful tool.

AppDelegate property or Singleton Object?

This is more of a design best practice question:
When you are designing the structure of lets say a location based app. The location Manager is obviously an important instance and should be given easy access for other objects.
Should you have it as a property of appDelegate? or a singleton on its own?
Under what scenario would you prefer one over the other?
I understand both would work, but I want to make sure I'm doing things the right way, not just hacking everything together.
Your inputs are much appreciated!
Neither.
Pass in a location manger object via a custom init method or property where ever you need it.
This will conform with the SOLID principals S, O & D (single responsible, open-close, dependency inversion).
Also testing with mocks will be possible more easily.
The worst choice IMO is to store things in the app delegate. See What describes the Application Delegate best? How does it fit into the whole concept? for much more on that. In short, the app delegate is the Application Delegate. It is not "the Application Dumping Ground for Globalish Things."
Singletons are a long-established approach in ObjC, via the shared... pattern. After decades of popularity, and extensive use within the core Cocoa frameworks (NSUserDefaults, NSNotificationCenter, NSApplication, NSFontManager, NSWorkspace, UIDevice, etc. etc. etc.), they have in recent years fallen into some disregard in favor of other techniques, particularly "dependency injection," which is just to say "assigning to a property."
After years of using singletons in ObjC, I am coming around to the DI way of thinking. The improvements in testability and the improved clarity of dependencies are quite nice. That said, sometimes DI can lead to awkward transitions, particularly when dealing with storyboards.
So, I would say:
When practical, just construct objects and assign them to properties on the objets that need them.
If you have a lot to pass around, consider collecting them into a single "configuration" object and pass that around (but this hurts modularity somewhat).
If DI creates chaos (particularly if it leads to a lot of passing objects to things just so they can pass the object on to something else), or if it forces a lot of storyboard segue code that you could otherwise avoid, singletons are a well-established and well-respected pattern in Cocoa and are not wrong. They are a Cocoa Core Competency.
If you ever find yourself calling (MyAppDelegate *)[[UIApplication sharedApplication] delegate], then you're doing something wrong.
Make another singleton for location management. Single responsibility is a first principle of SOLID.
Think about do you really need it in AppDelegate ?
For Location Manager for example, no you don't. You better keep the location manager with all its related methods in a separate class to keep the singularity principle as #vladimir said, and to be able to reuse it later.
AppDelegate is responsible for handling what happens when the app launch and/or going to the background, initializing core data, registering to push notification and other 3rd party libraries like parse,...
Adding other things to appDelegate will make it grow larger by time and it would be very hard to maintain.
When to add things that don't belong to AppDelegate to it? I think when the app is small, you know it won't scale up, and you are required to favor time over clean code.
Check the AppDelegate responsibilities , and this answer by Matt
You can create multiple instances of CLLocationManager and use them wherever you need them.
If you create one instance and try to share it then you'll have trouble trying to forward the delegate methods around or try to re-implement them as notifications leading to a big mess.

Why is "didChangeValueForKey:withSetMutation:usingObjects:" overriding discouraged

The apple documentation for NSManagedObject discourages overriding of "didChangeValueForKey:withSetMutation:usingObjects:".
Why?
As long as I call [super ..] this seems to work. Is there a reason not to? Or is there a more efficient way of capturing changes to it's own relationships?
'Seems' to work... Doesn't mean it will always work. Apple 'strongly discouraging' things generally means that they aren't telling us something about how the code works behind the scenes and you could easily trip yourself up.
To manage changes you should usually use dependent keys or implement custom accessor methods.

A tool in Xcode to check wether a function retains or not?

I'm currently working on an iOs application, and there is this one thing that is such a pain in the... well, a pain anyway : I always have to check the documentation to know wether an object property is retained or not (for instance, the setDelegate of the UITextField assigns the delegate and doesn't retain it, whereas the setFont function retains... https://developer.apple.com/library/ios/#documentation/uikit/reference/UITextField_Class/Reference/UITextField.html)
It's... a pain. Is there a way to know such a thing directly in Xcode ?
Thanks in advance
Delegates are a special case because what you are setting as a delegate is usually an object which would have a lifetime exceeding or equal to the object it is delegating for (i.e, a view controller would be the delegate of a text field). Because of this design pattern delegates are assigned, not retained, to avoid retain cycles. If you are creating a new object to act as the delegate for some other object, then you would have to retain it, but it doesn't quite smell right to be doing it that way.
For the rest of the cases, I really don't understand what your issue is, or why you are checking the documentation. You don't need to care about the retaining or otherwise that framework objects do to their properties. You only need to care about the retains and releases that you have made in your own code.
Do you have an example of a non-delegate property in a UIKit object that you have to retain yourself because the UIKit object is not retaining it?
I'm new to Objective C. But I think you don't really need to know. You just pass the property and it's up to the class (UITextField in this case) to retain it or not. You don't have to keep it around after passing it unless you need it for something else.
Also, try switching to ARC, a lot less of headaches for beginners.
Easy answer: switch to supporting iOS5 only and use ARC. You (mostly) don't need to worry about this kind of thing.
But, really, you don't need such a tool anyway. The conventions are very simple.
If you alloc, retain or copy something, you need to release it at some point
Otherwise you don't
Delegates are, in practice, no different. Why? Well, the delegate has to be around at least as long as the object with the delegate. So, unlike your setFont: example, you are very unlikely to do alloc; delegate = ...; release.

Why does Apple documentation that getting ManagedObjectContext from UIApplicationDelegate is bad?

Just curious why ManagedObjectContexts should be passed to UIViewControllers when they are created, rather than just grabbing them from a UIApplicationDelegate?
The docs say that this makes your applications more rigid, but I am failing to see the nuances of when to use which pattern.
Thanks!
Imagine that I ask you to do some task, like painting a room. If I just tell you "go paint a room," you'll need to ask me a lot of questions, like:
Which room?
Where's the paint?
Where are the brushes?
Should I use a dropcloth?
In short, you won't be able to complete the task without help from me. If you have to depend on me every time, you won't be a very flexible painter. One way to deal with that problem is for me to give you all the stuff you need at the outset. Instead of "go paint a room," I'll say "please paint room number 348 using this bucket of paint and this brush, and don't bother with a dropcloth." Now, you've got everything you need, and you can get right to work with no further help from me. You're a much more flexible worker because you no longer depend on me.
The same thing applies to view controllers (and objects generally); it's better to give them everything they need than to have them depend on a particular object like the app delegate. It's true not just for managed object contexts, but for any information they need to do their job.
This is mainly because you want to use dependency injection with your UIViewControllers instead of just grabbing everything from UIApplication, this keeps your delegate clean instead of full of reference hacks.
This is also to keep with the MVC pattern:
Model
View Controller (Only for view logic)
Controller (For coordinating between the view and the model)
I tend not to agree with this pattern.
First of all I try to treat Core Data as an implementation detail, and as any implementation detail it should be hidden behind a good facade. The facade is the interfaces I expose for my model objects. For example if I have two model objects; Cource and Student, any cource can have a number of students. I do not want to let the controller take upon the duty to setup predicates and sort descriptors, and jump through all Core Data hoops just to get a list of students for a particular class. There is a perfectly valid way to expose this in the model:
#interface Cource (StudentAccess)
-(NSArray*)studentsStortedByName;
#end
Then implement the ugly stuff once and for all in the Model class. Hiding all the complex details of Core Data, and no need to pass around managed object contexts. But how would I find the sources, it has to start somewhere right? Yes, it does but you need not expose it to the controller. Adding methods such as these are perfectly reasonable as well:
#interface Cource (CourceAccess)
+(Cource*)caurceByID:(NSString*)courceID;
+(NSArray*)allCources;
+(NSArray*)courcesHeldByTeacher:(Teacher*)teacher;
#end
This also helps in minimizing dependencies between controllers. And reducing he dependencies between the model and controller. Assuming I have a CourceViewController and a StudenViewController is I did not hide the Core Data details behind a facade and wanted to pass around the managed object context as well, then I would end up with a designated initializer like this:
-(id)initWithManagedObjectContext:(NSManagedObjectContext*)moc
student:(Student*)student;
Whereas with good a good facade I end up with this:
-(id)initWithStudent:(Student*)student;
Minimizing dependencies behind facades, in favor of dependency injection also makes it much easier to change the internal implementations. Passing around the managed object context encourages each controller to implement their own logic for basic stuff. Take for example studentsSortedByName method. At first it might be sorter by last/first name, if later changed to last/first name sort you would have to go to each and every controller that has sorted students and make the change. Where a good facade method requires you to change in one method, and all controller automagically get the update for free.
The Apple Docs try to foster the most widely applicable and sustainable design patterns.
Dependency injection is preferred because it allows for the most flexible, expandable, reusable and maintainable design.
As apps grow in complexity, using a quasi-singleton like parking the context in the app delegate breaks down. In more complex apps, you may have multiple context tied to multiple stores. You might want the same view-controller/view pair to display data from different context at different times or you may end up with multiple context on different threads/operations. You can't pile all those context up in the app delegate.
If you have a simple app with a single context then using the quasi-singleton with the app delegate can work well. I've used it on several smaller apps in the past without immediate issue but I did hit scalability problems on a couple of apps when the apps grew overtime.
Which pattern to use depends on your shipping constraints and you best guesses about of the evolution app over its entire lifecycle. If its a small one shot app, then the app delegate quasi-singleton will work fine. If the app is more complex, might grow more complex or might spawn other related apps that will reuse existing components, then dependency injection is the way to go.

Resources