I am a C# developer getting started on Objective-C / Cocoa Touch programming. I think I might have gotten some terms wrong because I keep thinking about them "the C# way". Specifically, I have come around the term "protocol" in various documentation and tutorials.
In Objective-C, what exactly is a protocol ? Can it be compared to a C# interface ?
Is the following declaration the same as saying "The class is implementing the protocol UITextFieldDelegate" ? Or is UITextFieldDelegate to be compared with a generic type parameter in C# ?
@interface MyViewController : UIViewController <UITextFieldDelegate> { }
Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. This chapter describes the syntax to define a formal protocol, and explains how to mark a class interface as conforming to a protocol, which means that the class must implement the required methods.
You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create. SPONSORED Get complete control over your app releases with Runway.
In Objective-C, protocols are declared with the “@protocol” keyword. Below is an example of declaring a protocol containing one required method. In Swift, the syntax is a little different but the idea is the same. In Objective-C, you add the protocol name in angle brackets beside the class interface declaration.
You can have properties in a protocol, provided every class that conforms to your protocol have a corresponding @synthesize for that property, or provide a getter and setter. But with a class category you generally can't add instance variables to a class.
In Objective-C a protocoll is the name for a collection of selectors/methods and is like an interface declaration in Java (probably also in C#).
@interface MyViewController : UIViewController <UITextFieldDelegate> { }
means that the class MyViewController
inherits from the class UIViewController
and adopts/implements the protocol UITextFieldDelegate
.
This means that MyViewController
must implement all methods declared in the UITextFieldDelegate
.
EDIT: It seems that with the introduction of Objective-C 2.0 the possibility to mark methods of a protocol as @optional
and @required
was introduced.
See section Optional Protocol Methods
of Apples Objective-C documentation.
Helpful link from wikibooks about Objective-C Protocols.
The protocol is like an interface in some aspect. If you declare some method in protocol to be optional, the class adopt it doesn't need to implement those methods. If not, the class have to implement it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With