Delegate ivar explanation - ios

What exactly does this line do:
id <ViewControllerDelegate> delegate
It's always declared as an instance variable in the viewcontroller that implements the delegate protocol, don't understand what it does though.
Thanks

It means delegate is an object which implements ViewControllerDelegate protocol methods. It helps the compiler to know the methods delegate is supposed to implement.
It's useful for checking type safety at compilation time and helps with autocompletion too.

It means that any methods or properties declared in the protocol can also be handled in the delegate. Typically setting a delegate would mean that those delegate methods are called by any instances that conform to the protocol.
A table view, for example, requires you to implement a delegate, typically on 'self'. Doing so means you inherit those properties and / or methods provided in that protocol. This is how you get those magical, - (UITableView *)table... methods. That's the basic idea of it.
Also, you can take a look at this answer. Hope that helps!

Related

How the UITableViewDelegate and UITableViewDataSource methods get automatically called?

Just conforming to the datasource and delegate protocol and assigning the delegate and data source object in my class implementation file and defining the methods defined under the datasource and delegate protocol is all anyone need?How does those methods get called automatically?
It's just a kind of design pattern, which expose to you as many methods as needed to give you enough flexibility to control it and hide from you all the hard work.
Since you're assigning self to delegate and datasource properties, that mechanism is just calling those exposed protocol method on object which is the "self". Those methods are called while it's building up dynamic content, while reloading, etc.
If you're interested with implementation, you could check this open class with the same design pattern:
iCarousel

Why a delegate work also without defining it in the interface file?

I have a simple question to ask.
I have a ViewController that use a UITableView to show a list of things. The UITableView delegates are the this ViewController (using dataSource = self, etc..)
In all tutorials i know that i need to define the delegate class in the interface using:
#interface Class : SuperClass <ClassNameDelegate>
But all the code works good also without declaring this and implementing only the methods. For example:
#interface Class: SuperClass
Is a bug? I need to declare it anyways?
Thank you.
Mauro
In common case we use performSelector to call delegate methods like this:
[(NSObject *)_delegate performSelector:#selector(storeFeedbackViewControllerWasDismissed)];
and everything works because this delegate have got this method.
But it's better to point that class conforms protocol because XCode can warn you to implement required delegate methods that you can miss.
There is three moments:
Yours second class will return NO for call conformsToProtocol:#protocol(ClassNameDelegate)
If ClassNameDelegate have required methods, you will not get compilation second class error if it's not implement requited methods.
You will get warning if try assign object of second class to id<ClassNameDelegate>

What exactly are protocols and delegates and how are they used in IOS?

I'm really confused about the concept of delegates and protocols. Are they equivalent of interfaces and adapter classes in Java? How do they work?
None of the resources I've read were helpful so far.
"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." I have no idea what this means.
Can someone please explain what they are and give a simple example? Thanks in advance!
EDIT:
As far as I now understand,
1) delegates implement protocols (another name for interfaces)
2) object registers a delegate (that implements a protocol)
3) object can call protocol methods on the delegate
Therefore, a delegate is connecting the object with the protocol.
Please correct me if I'm wrong.
I still don't understand why the object itself can't implement a protocol? It could've been so much easier!
Protocols are a way to specify a set of methods you want a class to implement if it wants to work with one of your classes. Delegates and Data Sources like UITableViewDelegate and UITableViewDataSource are protocols indeed.
You specify a protocol this way:
#protocol MyProtocol <NSObject>
- (void)aRequiredMethod;
#required
- (void)anotherRequiredMethod;
#optional
- (void)anOptionalMethod;
#end
Methods declared after the #required or before any other specifier are required and the classes that want to use your protocol need to implement all of them. You can also declare some optional methods by declaring them after the #optional specifier.
You then can specify that a class "conforms" to a protocol (implements the required methods) in the interface of the class:
#interface MyClass <MyProtocol>
#end
You usually keep a reference to an object conforming to a protocol using a property. For example, to keep track of a delegate:
#property (nonatomic, weak) id<MyProtocol> delegate;
At this point, in your code, you just have to call the method you want to call on the object that you're keeping reference of and that implements your protocol as you would with any other method:
[self.delegate aRequiredMethod];
To check whether an object conforms to a protocol you can call
[self.delegate conformsToProtocol:#protocol(MyProtocol)]
To check whether an object implements a method you can call
[self.delegate respondsToSelector:#selector(anOptionalMethod)]
For more information, check the Apple's guide Working With Protocols.
A protocol which declared with the (#protocol syntax in Objective-C) is used the declare a set of methods that a class that "adopts" (declares that it will use this protocol) will implement. This means that you can specify in your code that, "you don't care which class is used so long as it implements a particular protocol". This can be done in Objective-C as follows:
id<MyProtocol> instanceOfClassThatImplementsMyProtocol;
If you state this in your code, then any class that "conforms" to the protocol MyProtocol can be used in the variable instanceOfClassThatImplementsMyProtocol. This means that the code that uses this variable knows that it can use whichever methods are defined in MyProtocol with this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.
Delegates are a use of the language feature of protocols. The delegation design pattern is a way of designing your code to use protocols where necessary. In the Cocoa frameworks, the delegate design pattern is used to specify an instance of a class which conforms to a particular protocol. This particular protocol specifies methods that the delegate class should implement to perform specific actions at given events. The class that uses the delegate knows that its delegate coforms to the protocol, so it knows that it can call the implemented methods at given times. This design pattern is a great way of decoupling the classes, because it makes it really easy to exchange one delegate instance for another - all the programmer has to do is ensure that the replacement instance or class conforms to the necessary protocol (i.e. it implements the methods specified in the protocol)!
Protocols and delegates are not restricted only to Objective-C and Mac/iOS development, but the Objective-C language and the Apple frameworks make heavy use of this awesome language feature and design pattern.
Edit:
Please find this Example. In the UIKit framework of Cocoa Touch, there is a UITextFieldDelegate protocol. This protocol defines a series of methods that classes which are delegates of a UITextField instance should implement. In other words, if you want to assign a delegate to a UITextField (using the delegate property), you'd better make sure that this class conforms to UITextFieldDelegate. In fact, because the delegate property of UITextField is defined as:
#property(nonatomic, assign) id<UITextFieldDelegate> delegate
Then, the compiler will give warnings if you assign a class to it that doesn't implement the protocol. This is really useful. You have to state that a class implements a protocol, and in saying that it does, you're letting other classes know that they can interact in a particular way with your class. So, if you assign an instance of MyTextFieldDelegateClass to the delegate property of UITextField, the UITextField knows that it can call some particular methods (related to text entry, selection etc.) of your MyTextFieldDelegateClass. It knows this because MyTextFieldDelegateClass has said that it will implement the UITextFieldDelegate protocol.
Ultimately, this all leads to much greater flexibility and adaptability in your project's code, which I'm sure you'll soon realise after using this technology! :)
In it's simplest form a delegate is an object which receives messages from another object. And you do it all the time.
So say you had car object with an engine.
#interface car : NSObject
#property (nonatomic) id engine;
#end
So could forward a start message to the engine.
[_engine start];
The engine is acting as a delegate, you're just passing it a message.
Protocols make it more formal, and Xcode will check that you are conforming to the required or optional methods.
#property (nonatomic) id <engineDelegate> engine;
says that the engine object MUST contain the function start because in the the protocol definition it asked for it.
#protocol engineDelegate
- (void) start;
#optional
- (double) fuelLevel;
#end
Why are delegates and protocols so cool? Well because the engine could be any number of different engines which you could use at runtime, it could be a jet engine, a combustion engine, a phasing modulating engine it doesn't matter, as long as it conforms to the protocol. And you tell Xcode that it does conform by adding the delegate to the class interface.
#interface timeWarpDrive : NSObject <engineDelegate>

Are these points about delegates in IOS correct? Yes or no?

I've been struggling with delegates for a long time. It's a very hard concept for me for some reason. I feel like now I have more knowledge, but I'm still far from being confident.
Please tell me if any of these are incorrect/incomplete and why. Thank you.
Delegates implement protocols (unimplemented method headers)
An object (a delegator) can register a delegate (that implements a protocol). This can be done by declaring a property of type id that implements a protocol:
#property (weak, nonatomic) id <MyProtocol> myDelegate;
The delegator can call certain methods (as specified in MyProtocol protocol) on the delegate
Any class that implements the protocol and has to be Delegator's delegate, can declare itself as such:
MyDelegator* myDelegator = segue.destinationViewController;
myDelegator .delegate = self;
Advantages of using a delegate:
a. Reduces coupling (Delegate and Delegator are no longer dependent on each other) which is an important OO design principle
b. makes Delegator more generic; it can now work with other objects, not just this Delegate
1,2 - yes
3 - can call any method of MyProtocol,
4 - correct.
5 - almost right, a very good explanation can be found here delegate and controllers
Yes. But the protocols can be informal.
Yes.
Yes.
Yes and no. Again, the delegate could implement the methods informally... but then you'd want the delegator to verify if the delegate respondsTo (or implements) a method before calling it.
The delegate doesn't necessarily need to set itself as the delegator's delegate (in fact, it shouldn't). Analogy: A business specialist comes to my company and tells my boss to delegate the administrative paperwork to his secretary. The secretary (the delegate) didn't tell the boss (the delegator) to give it work... a third-party did.
A delegate doesn't have to register itself as the delegate (again, it shouldn't). It needs only be able to do the work. Normally the delegate would know nothing (no pointers to) the delegator. So the delegate wouldn't have MyDelegator* myDelegator = segue.destinationViewController;, no.
A) Yes!
B) Yes. Essentially what "reduce coupling" is;
Adding a C): It also allows you to change the behaviour on-the-fly by simply changing the delegate at runtime.

Is it necessary to declare an object as a delegate to use it as such?

I made a NSURLConnection with the calling class as the delegate.
I built this on to my test device before realizing I never declared the object as observing the protocol, but it ran (I would say normally, but I think I totally screwed my app around multiple threads).
So is it not necessary to declare an object as implementing a delegate?
I also did not include all the required delegate methods, and it still called the delegate methods.
There are other people on this project, and its fairly large so maybe the delegate protocol is declared somewhere obscure, but I didn't see it while searching for it in the header and implementation declarations.
The delegate parameter of the NSURLConnection initWithRequest:delegate: method is defined with a type of id<NSURLConnectionDelegate>.
If you pass an object that does not declare that it conforms to the NSURLConnectionDelegate, you should get a compiler warning indicating that you are passing the wrong kind of object. Double check to see if you get any sort of warning. If not, then somewhere your class properly declares it conforms to the protocol.
At runtime, the only requirement is that the delegate object actually implements at least the required methods of the delegate. But in this case there are no required methods in the protocol. They are all optional.
You state: "I also did not include all the required delegate methods, and it still called the delegate methods." This doesn't make sense. How can they be called if you don't implement them? Plus, there are no required methods in the protocol.
I think it depends on how NSURLConnection is implemented. First, if the setDelegate: method/property is set to accept an object of type id<NSURLConnectionDelegate>, then the compiler should warn you. If the NSURLConnection source code checks the delegate with (for example) +conformsToProtocol: before calling any protocol methods on it, then your object shouldn't be called back.
EDIT: rmaddy adds that all methods in the protocol are optional. Being that the case, then NSURLConnection most likely checks with (instance)-respondsToSelector: instead of (class)+conformsToProtocol:. In which case, having implemented the method should be enough (but you should still get warnings on -setDelegate:)
Despite what the documentation says, if you look at Cocoa's actual definitions of initWithRequest and connectionWithRequest, they are defined as follows:
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
As you'll see, the delegate parameter is defined as id without any explicit, formal protocol specified, and as such, you won't get an warning if the object you pass to it doesn't happen to be defined as conforming to any particular protocol.
So, in answer to your question, in this particular case, you don't have to define the delegate to conform to any particular protocol. In many other cases, the delegate property is defined to take a pointer that conforms to the appropriate protocol, so the compiler will warn you if your object doesn't conform. But not in this case.
Needless to say, you probably should go ahead and define to which protocols you're conforming because it makes you code more clear and you'll enjoy, at the very least, better auto-completion in Xcode when you start to write one of these methods. But your question wasn't whether you should (which you should), but rather whether you must (which you don't).
And just as a clarification, in iOS, there are now two NSURLConnection protocols, NSURLConnectionDataDelegate and NSURLConnectionDelegate. (This may be why they don't define the protocol in the method declarations, to avoid confusion with their shifting of some methods into this NSURLConnectionDataDelegate protocol.)

Resources