Who is whose delegate? - ios

I am a new learner of iOS and I am reading "iOS Programming 4th Edition-Big Nerd Ranch",there is a question while I am reading the 7th chapter.
it says
A button’s life is relatively simple. For objects with more complex lives, like a text field, Apple uses the delegation pattern. You introduce the text field to one of your objects: “This is your delegate, when anything interesting happens in your life, send a message to him.” The text field keeps a pointer to its delegate. Many of the message it sends to its delegates are informative: “OK, I am done editing!”.
It makes me confused,because at first,it means that the text field can be introduced to one of my objects as a delegate of them,but finally it says " the text field keeps a pointer to its delegate ". Isn't the text field itself a delegate of others,is it? So I don't understand who is whose delegate ? Does it mean that the text field can be delegate of others,but it can also have delegate of itself? or else?
Thanks in advance!

Your object is the delegate. The text field will be sending the messages to it.

Understand what delegate means: It's your delegate -- acting on behalf of your program logic, and interacting with the UI object to tell it what you want done. In a sense ambassador would be a better title, since it's representing you in some "remote" location.
Just as there might be a US ambassador to Thailand, your program might have an ambassador to the UITextField object. When you create the UITextField you tell it what object is it's ambassador/delegate and then the UITextField talks to that object when it needs to know what you want to do.

Many of Apple's framework objects take a delegate. A delegate is a pointer to some anonymous object that you know very little about. All you know about it is that it understands a certain set of calls (a protocol). It's like a private lingo.
The idea is that the system object sends information to the delegate to either tell it about what has happened (the user selected the picker item at index 4) or ask it about how it should behave (The user wants to scroll to the left. Should I allow it?)
By using the delegate design pattern, you can build general-purpose objects that can be used in a wide variety of situations, by a wide variety of different objects.
When you read delegate, think "customer". A system object is a shopkeeper. Its delegate is a customer.
The shopkeeper doesn't need to know much about his customer. He takes an order for a product, calls out the customer's number when the order is ready, hands over the product, takes some money, and moves on. The customer doesn't even have to speak very much of the shopkeeper's language - only enough to place the order, understand when the order is ready, and how to pay for it.
The protocol is the language that the object (shopkeeper) uses to talk to it's delegate (customer). It's a limited, formally defined language. Any delegate (customer) who understands the required words in the object's (shopkeeper's) language (protocol) can get services from the object (shopkeeper).
BTW, you should accept the answer that helped you first and/or best, and up-vote all answers that you find useful. In this case I think you should accept #MirekE's answer. He was the first one to give you a clear answer.

Related

Is the use of id type in method a good practice?

I am creating a set of API and some users have suggested that I use id type for a particular method that can accept custom object (defined by the API) or string instead of creating two versions. Is the use of id type in method a good or acceptable practice? Does Apple do it with their any of their API?
That would be very poor practice. If you're creating an API you need to retain full control, and allowing users to pass any object to your method at which point you would have to cast it to that object or string you mentioned could be fatal depending on what's passed. Creating two methods with different parameters is not only okay, but follows the tenets of polymorphism to the T.
Accepting id is not in itself good or bad practice. How much manual procedural if/then/else/if/then/else nonsense will you acquire? If quite a lot then something is wrong.
Put another way: if the conditional logic related to different kinds of object ends up being implicit, via the Objective-C dispatch mechanisms, then the design is good. If you end up impliedly reimplementing dynamic dispatch then you've gone completely wrong.
Apple does it frequently. Just off the top of my head there are:
as per Nikolai's comment, all the collection types: set, dictionary, array, etc.
anything that takes %# as a format specifier: NSLog, certain methods on NSString, etc.
anything that still uses an informal protocol.
anything in or semi-close to the runtime like key-value coding.
archiving and the user defaults.
anywhere that storage is offered for your own use — the hardy userInfo on NSTimer and the rest.
anywhere that target/action is used — all UIControls, the notification centre, etc.
As per my comment, suppose your custom class had this method:
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
And suppose it were the only method being called by whomever is being passed either a string or your custom object. Then id would be the right choice, since you'd have in effect implemented an informal protocol, and the thing being passed an object genuinely doesn't care whether it's a string or not. The only contractual requirement is the informal protocol and the protocol is informal i.e. has no footprint on the type syntax.
Conversely, suppose your custom class had no methods in common with NSString and your code just looked like:
- (void)myMethod:(id)object
{
if([object isKindOfClass:[NSString class]])
[self myMethodOnString:object];
else
[self myMethodOnCustomClass:object];
}
Then id would be inappropriate. You're just obscuring what the method does and implicitly reproducing work that's built into the runtime anyway.

I need to understand why delegation in Objective-C is so important, what makes it so special?

So I've read about delegate explanation and practices a lot, but I still seem to not get it, I have specific questions and I would love to have some insightful simple answers.
Why use delegate over instance method? In UIAlertView why not just make – alertView:clickedButtonAtIndex: an instance method that will be called on my UIAlertView instance?
What is the delegate property? why do I have to make delegate property and define it with that weird syntax #property (nonatomic, strong) id <ClassesDelegate> delegate
Is delegate and protocol are two faces for a coin?
When do I know I should implement delegate in my app instead of direct calling?
Is delegate used as much and as important in Swift?
What gets called first and why? The method in the class who made himself a delegate? or the delegate method itself in class where it is declared?
Thank you for taking the time to go through this, I am desperately looking for a clear and helpful answers to my questions, feel free to give example or cover some related topic!
The advantage of delegation is Dependency Inversion.
Usually code has a compile-time dependency in the same direction of the run-time calling dependency. If this was the case the UITableview class would have a compile-time dependence on our code since it calls our code. By using delegation this is inverted, our code has a compile-time dependency on the UITableview class but the UITableview class calls our code at run-time.
There is a cost involved: we need to set the delegate and UITableview has to check at run-time that the delegate method is implemented.
Note: When I say UITableview I am including UITableviewDelegate and UITableviewDatasource.
See: Dependency inversion principle and Clean Code, Episode 13.
Maybe a real life example can better describe what's different in the delegation design pattern.
Suppose you open a new business, and you have an accountant to take care of the bureaucratic stuffs.
Scenario #1
You go to his office, and give him the information he needs:
the company name
the company # number/id
the number of employees
the email address
the street address
etc.
Then the accountant will store the data somewhere, and will probably tell you "don't forget to call me if there's any change".
Tomorrow you hire a new employee, but forget to notify your accountant. He will still use the original outdated data you provided him.
Scenario #2
Using the delegation pattern, you go to your accountant, and you provide him your phone number (the delegate), and nothing else.
Later, he'll call you, asking: what's the business name?
Later, he'll call you, asking: how many employees do you have?
Later, he'll call you, asking: what's your company address?
The day after you hire a new employee.
2 days later, he'll call you asking: how many employee do you have?
In the delegation model (scenario #2), you see that your accountant will always have on demand up-to-date data, because he will call you every time he needs data. That's what "don't call me, I'll call you" means when talking of inversion of control (from the accountant perspective).
Transposing that in development, for example to populate a table you have 2 options:
instantiate a table control, pass all the data (list of items to display), then ask the table to render itself
instantiate a table control, give it a pointer to a delegate, and let it call the delegate when it needs to know:
the number of rows in the table
the data to display on row no. n
the height the row no. n should have
etc.
but also when:
the row no. n has been tapped
the header has been tapped
etc.
Firstly, don't feel bad that all if stuff isn't clear yet. This is a good example of something that seems tricky at first, but just takes time really click. That will happen before you know it :-). I'll try and answer each of your points above:
1) Think of it this way - the way UIAlertView works now, it allows Apple to “delegate” the implementation of the alertView:clickedButtonAtIndex: to you. If this was an instance method of UIAlertView, it would be the same implementation for everyone. To customize the implementation would then require subclassing - an often over relied upon design pattern. Apple tends to go with composition over inheritance in their frameworks and this is an example of that. You can read more on that concept here: http://en.wikipedia.org/wiki/Composition_over_inheritance
2) The delegate property is a reference to the object which implements the delegation methods and whichs should be used to “delegate” those tasks to. The weird syntax just means this - a property that holds a reference to an object that adheres to the protocol.
3) Not quite - delegation leverages protocols as a means for it’s implementation. In the example above, the is this the name of a protocol that an object which can be considered a delegate for that class must adhere to. It is inside that protocol that the methods for which a delegate of that class must implement are defined. You can also have optional protocol methods but that’s a different topic.
4) If I understand the question correctly, I think a good sign that you may want a delegate to be implemented instead of simply adding instance methods to your object is when you think that you may want the implementation of those methods to be easily swapped out or changed. When the implementation of those methods changes considerably based on where/how the functionality your building is being used
5) Absolutely! Objective-C and Swift are programming languages and the delegation pattern is an example of a design pattern. In general design patterns are hoziontal concepts that transcend across the verticals of programming languages.
6) I’m not sure I understand you exactly but I think there’s a bit of misunderstanding in the question - the method does not get called twice. The method declared in the delegate protocol is called once - typically from the class that contains the delegate property. The class calls the delegates implementation of that property via something like:
[self.delegate someMethodThatMyDelegateImplemented];
I hope some of this helped!
Sometimes you want your UIAlertView to work different in different contexts. If you set your custom UIAlertView to be delegate of itself it has to provide all those contexts (a lot of if/else statements). You can also set seperate delegate for each context.
This way you say to your compiler that every class (id) which implements protocol ClassesDelegate can be set to this property. As a side note it should usually be weak instead of strong to not introduce reference cycle (class A holds B, and B holds A)
Protocol (interface in other languages) is used to define set of methods which should be implemented by class. If class conforms to the protocol you can call this methods without knowledge of the specific class. Delegate is pattern in which class A delegates some work to class B (e.g. abstract printer delegates his work real printer)
When you need few different behaviours which depends on context (e.g. ContactsViewController needs to refresh his list when download is finished, but SingleContactViewController needs to reload image, labels etc.)
It is one of the most fundamental patterns in programming, so yes.
It's the same method
You can't just add a method to UIAlertView, because you don't have the source code. You'd have to subclass UIAlertView. But since you have more than one use of UIAlertView, You'd need several subclasses. That's very inconvenient.
Now let's say you use a library that subclasses UIAlertView, giving more functionality. That's trouble, because now you need to subclass this subclass instead of UIAlertView.
Now let's say that library uses different subclasses of UIAlertview, depending on whether you run on iOS 7 or 8, and UIAlertview unchanged on iOS 6. You're in trouble. Your subclassing pattern breaks down.
Instead, you create a delegate doing all the things specific to one UIAlertview. That delegate will work with the library just fine. Instead of subclassing a huge and complicated class, you write a very simple class. Most likely the code using the UIAlertview knows exactly what the delegate should be doing, so you can keep that code together.

UILexicon in Objective-C

How do you use UILexicon in Objective-C? I find the documentation Apple provides is extremely unhelpful.
What does it do? Does it return a dictionary or proper spellings of words? Or do I provide a word like "hellllo" and it matches it with the proper spelling "Hello" and returns that as a string?
Any help would be appreciated.
requestSupplementaryLexiconWithCompletion:
Here's my error report, but obviously I'll have errors because I'm completely guessing how to use the function, no clue what goes inside the block statement (because the docs (at the time) don't say! (Beta 4 docs)) Hahahah!
I've never used this feature, but a quick web search for "UILexicon" landed me in Apple's documentation; reading and following links from there filled in the picture pretty quick.
App Extension Programming Guide has a quick explanation of what lexicons are for:
Every custom keyboard (independent of the value of its RequestsOpenAccess key) has access to a basic autocorrection lexicon through the UILexicon class. Make use of this class, along with a lexicon of your own design, to provide suggestions and autocorrections as users are entering text.
Clicking the UILexicon link on that page took me to the reference doc for that class, which explains that it's a read-only list of Apple-provided term pairs. Each of its entries is a UILexiconEntry object -- the docs for that class say it provides a userInput (what the user typed, e.g. "ipad") and a documentText (what to substitute for it, e.g. "iPad"). Since those classes are read-only, it follows that they're probably not a way for you to provide your own autocorrection pairs -- as stated in the docs, they're for supplementing whatever autocorrection system you implement.
At this point, I don't even have to look at the doc for requestSupplementaryLexiconWithCompletion: to get a good idea how to use it: just the declaration tells me:
It's a method on UIInputViewController, the class I'd have to subclass to create a custom keyboard. Somewhere in that subclass I should probably call it on self.
Its return type is void, so I can't get a lexicon by assigning the result of a requestSupplementaryLexiconWithCompletion call to to a variable.
It calls the block I provide, passing me a UILexicon object as a parameter to that block.
It's got words like "request" and "completionHander" in it, so it'll probably do something asynchronous that takes awhile, and call that block when it's done.
So, I'm guessing that if I were writing a custom keyboard, I'd call this method early on (in viewDidLoad, perhaps) and stash the UILexicon it provides so I can refer to it later when the user is typing. Something like this:
#property UILexicon *lexicon;
- (void)viewDidLoad {
[super viewDidLoad];
[self requestSupplementaryLexiconWithCompletion:^(UILexicon *lexicon){
self.lexicon = lexicon;
}];
}
Because it's unclear how long requestSupplementaryLexiconWithCompletion will take to complete, any place where I'm using self.lexicon I should check to see if it's nil.
Back in the App Extension Programming Guide, it lists "Autocorrection and suggestion" under "Keyboard Features That iOS Users Expect", right before saying:
You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed
So it sounds like autocorrection is something you have to do yourself, with your own UI that's part of the view presented by your UIInputViewController subclass. The API Quick Start for Custom Keyboards section in the programming guide seems to hint at how you'd do that: use documentContextBeforeInput to see what the user has recently typed, deleteBackward to get rid of it, and insertText: to insert a correction.

iOS: Pattern for mapping view inputs to NSManagedObject

I am building an app with a view controller that represents a form for creating and editing a Task object. It has the following behaviour:
On initialization of the controller, a Task object (NSManagedObject subclass) is initialized in the MOC
NSNotificationCenter observers are set up for each input in the view.
When an input's value is changed, the corresponding property of the Task object is updated via the observers' assigned method. (eg. - (void)taskNameChanged;)
When the user taps Save, the Task object is committed to the data store. If the user taps cancel, the Task object is discarded from the MOC.
I have a feeling that there is a better way to do this. What is the most common pattern for this type of transaction?
It's uncommon to use notifications in cases like this. The question you need to ask is: Do you need to update it all the time? Most of the times you won't. I usually just the values when the Save button is tapped.
In case you would have to check the values earlier, you still don't want to use notifications. I usually go for hooking up a IBAction to one of the events in Interface Builder. Another option is using the delegate, in that case your UIViewController instance would implement the UITextFieldDelegate protocol.
Unfortunately, iOS lacks Cocoa Bindings, so you end up having to implement a light version yourself.
I did this for our app, and it ended up working well. I used KVO instead of notifications, for two-way binding. I created a dictionary mapping between the object properties and UI elements, and using KVC set up the binding when the view is loaded. In my implementation, I added an option to hint which value should take precedence (this is less valuable for data<->UI, but I wanted something more generic). Eventually, I added support for block-based data transformation between binded objects, so that UI could present text, while the data backing object could hold different types of data.
Please note that UIKit is not KVO compliant. I created KVO-compliant versions of UITextField and UITextView, by listening to notifications and sending the appropriate KVO messages.
While, I cannot post code of this, I hope this gives you ideas regarding your further adventures.

Why only one delegate?

I've read that an object can only have one delegate at once.
But is that really true?
Let's say I make an object with a protocol and from that object I want to gather a lot of data from several other objects. I add every object that conforms to my protocol to an array. Then I just loop through it and call my methods on every delegate.
NSMutableArray *collectFromDelegates = [NSMutableArray alloc]init];
//in delegateArray I keep pointers to every delegate.
for(id delegate in delegateArray){
[collectFromDelegates addObject:[delegate someProtocolMethod]];
}
Is this wrong?
That's not really delegation.
Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled.
It doesn't make much sense to have more than one object handle an event for you, since it has already been handled. The only reason I could see to have multiple delegates is that if the first fails to handle an event, it can be passed to the next, continuing until some object handles it.
In your example, the objects are acting as data sources. This makes more sense than multiple delegates, but could easily be implemented by having a single data source combine data from multiple objects, which means the object asking for the data doesn't have to worry about how to combine it.
The other case where you would often want multiple objects is receiving notifications of an event. This is not delegation because the objects are not working for the object, just acting on something that happened to the object. This is better implemented using notifications or observing.
Apple's convention is to only have one "delegate" object. But you can set up your own class to have an array of delegates if that's what you need. You might want to call them something else for clarity.
In your example, calling them "dataSources" might be more appropriate.
A class only really needs one delegate, if you have more than one you are solving a different problem. The delegate pattern is used to modify the behaviour of a class. Say for instance we have a Dog class which can bark, but different types of dogs bark in different way. A delegate would be one way of changing the barking behaviour.
If you need more than one you are probably more interested in OBSERVING what your class is doing, it needs to NOTIFY others of current EVENTS. As several other classes might be interested in the behaviour of one you would need an array. In iOS SDK this is already done for you with notifications. This is called the Observer pattern.
Different use cases...
I've read that an object can only have one delegate at once. But it's that really true?
Where did you read that? No, it's not true. For instance, UITableView has two delegates, one to supply the data, the other to handle actions.
A delegate is just an abstract concept - you can have as many delegates as you want. However, this is rarely required and often a poor pattern.
Apple make good use of a source and delegate pattern. Source ivars (a form of delegate) provide data, while delegate ivars are invoked for logical responses. Perhaps this is a better solution?
Alternatively you can use NSNotification to inform many listeners of a single event.
Hope this helps!
Generally, when you want to message multiple classes that are interested in what you class does, you would use NSNotifications. That will however not allow them to return data unless you allow them to send a message to the object of the notification. I'm not sure if that would be a cleaner solution though.
One approach beside the mentioned Notifications could be, that your delegate implementation holds an array of objects conforming to the protocol and calls the protocols method on this as a wrapper.

Resources