Reputation: 3709
So I'm trying to wrap my head around Objective-C interfaces, delegates and protocols. So I have a question:
Does a delegate have to be in a separate file or can it be methods defined in your class?
Is a protocol like a java interface? This is the way I understand it at the moment where it basically makes you implement methods if you use this protocol.
I'm still confused about interfaces. I'm pretty sure they have no resemblance to what an interface is in java. Maybe it's just a declaration of variables that will be implemented in the class.
Upvotes: 6
Views: 8866
Reputation: 640
I would suggest checking out:
The Objective-C 2.0 Programming Language
It should have the answer to most of your questions about protocols and interfaces.
As far as delegates, they can be a new object or the object in which you are creating the thing needing a delegate. Files don't really have anything to do with it.
Upvotes: 2
Reputation: 2146
The point of a delegate is to be notified when another object does something. For example one of your objects wants to know that a window is being closed, so you register it as the window's delegate and implement the windowWillClose:
method. It will be called by NSWindow
appropriately. So the delegate methods are usually defined in another class. Up to a certain point, it lets you extend the functionality of a class without subclassing it.
(Edit: see Daniel's answer about protocols.)
The @interface
is the class declaration, where the member variables and methods are listed. It's located in the .h
, that you import if you need to use the class. The code for methods sits in the @implementation
in the .m
file. In Java it's different, the .java
file serves both purposes.
Upvotes: 13
Reputation: 22395
A delegate protocol needs to be defined as such
@protocol
//methods
@end
it can be put in any .h class, you just need to import i t whenever you are going to use it.
A protocol is not like a java interface, a protocol is an adapter that allows two classes to works together. Basically it says, if you want class A to send you messages about its state and actions these are the methods it will call on its delegate that you must implement. Its not like an interface because an interface says if you want to subclass this class you must implement these methods, the protocol says if you want to interact with this class you must implement these methods, so its somewhat different.
Upvotes: 22