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.
Related
My IOS application includes similar views that draws data from server and visualise them.
I want to combine common networking code in a class to ensure reusability and to avoid repeated code.
Should I locate networking code in a super class or in an associated class. I couldn't make a decision which method should I use, generalisation or association (aggregation)?
What would you do if you were me?
It is not good solution to create view superclass for storing client-server communication code due causes:
Client-server communication isn't a part of data presentation (View). Logically it is separate entity.
If you use associated object you could use it anywhere, not only in Views that represent loaded data. It makes your architecture more flexible.
There are more reasons to not use inheritance in your case but I think these two points are enough to make decision.
To my mind you should use associated object (aggregation).
I need to create a global object that will work and can be used across all the classes in the program. I've done some research and seen the solution seems to be implementing it in the AppDelegate, but there doesn't seem to be much explanation as to how to accomplish this and more importantly this doesn't really seem correct as per my understand of the AppDelegate purpose.
you should check the singleton pattern:
In software engineering, the singleton pattern is a design pattern
that restricts the instantiation of a class to one object. This is
useful when exactly one object is needed to coordinate actions across
the system. The concept is sometimes generalized to systems that
operate more efficiently when only one object exists, or that restrict
the instantiation to a certain number of objects. The term comes from
the mathematical concept of a singleton.
here is a source for a example implementation: What should my Objective-C singleton look like?
In learning about Core Data, I've noticed how (in Xcode's templates) Apple directly used the query classes inside the view controller. This seems like it is bad MVC (having database access logic directly inside the view controller). Would it make sense to abstract out these kinds of actions to a separate suite of classes that obtain the data from the database and pass it back to the view controller calling it?
EDIT–
So, just to be clear, when I say "kinds of actions", I specifically mean CRUD Operations. Though if you have ideas about other things that a so-called "Model-Controller" would do, I'd be interested in hearing about them.
It's a matter of opinion, and often yes the templates are the most simple form of working example. It's hard to have a template spin out multiple files, for example.
Yes, personally, I generally spin out a separate NSManagedObject subclass. I like to have a _MySubclass object that has all the auto-generated stuff, then have the model actually reference MySubclass which has model-based business logic (you can use mogenerator or other methods to do this too if so inclined). Perhaps thinking of it as "Model-Controllers" and "View-Controllers" is another way of putting it.
This is a very good question and the answer likely depends on your situation. Perhaps architecture purists would insist on separate Model controllers and there are a lot of benefits to this approach. However, sometimes I find myself using Key Values when I'm doing a simple view. When things are more complex, for example, when coding the same Model for the Mac and iOS, having separate Model Controllers will allow you to reuse a lot of code. When you must diverge, Obj C Categories are a very clean way to extend functionality without adding a lot of overhead. I personally favor categories over extensive subclassing.
Since NSFetchedResultsController was released, my model classes are leaner. There are a lot of nuances to this and experience will help you come up with the best solution for your App. I've also found that writing unit tests up front will help you force through issues and validate your design, or send you back to the drawing board :)
A best practice in DI I've read in a few places is not to inject object B just to get at object C, but to inject C instead.
But if a single method from C is all that is required, would you just inject that method instead of C?
If so, what about if a few methods from C were required? Is there a point that it's just more convenient to pass in the full object and live with the fact that you're getting stuff you have no interest in?
Or does that point indicate that maybe class C has too many varied responsibilities and needs to be extracted into multiple smaller classes, the objects of which can then be injected without as much baggage?
Don't be afraid to state the obvious, this is all new to me.
If the dependency has (many) more methods than you care about, it's a pretty good sign that it's a Header Interface that violates the Interface Segregation Principle.
If you have control over the interface, I'd suggest splitting it up into several smaller Role Interfaces. You can still have one concrete class implementing more than one Role Interface if that makes more sense for your specific implementation.
If you don't control the design of the dependency, I'd tend towards injecting the whole interface, as it still represents a cohesive collection of behavior (even if we don't agree with the design choice of the original designer). You might need more of that behavior later on.
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.