25

Can anyone tell me what the angle brackets <...> in an Objective-C class interface do? Like this one (from http://snipt.net/robhawkes/cocoa-class-interface):

@interface MapMeViewController : UIViewController <CLLocationManagerDelegate, 
            MKReverseGeocoderDelegate, MKMapViewDelegate, UIAlertViewDelegate> { ... }

From my view they look like some sort of type declaration (considering my previous experience in PHP and JavaScript), like we're making sure MapMeViewController is a CLLocationManagerDelegate, MKReverseGeocoderDelegate, MKMapViewDelegate, or UIAlertViewDelegate

Documentation about the @interface syntax don't seem to mention this.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
robhawkes
  • 305
  • 1
  • 4
  • 10

4 Answers4

40

The angle brackets in a class interface definition indicates the protocols that your class is conforming to.

A protocol is almost like an interface in Java or C#, with the addition that methods in an Objective-C protocol can be optional.

Additionaly in Objective-C you can declare a variable, argument or instance variable to conform to several protocols as well. Example

NSObject<NSCoding, UITableViewDelegate> *myVariable;

In this case the class must be NSObject or a subclass (only NSProxy and its subclasses would fail), and it must also conform to both NSCoding and UITableViewDelegate protocols.

In Java or C# this would only be possible by actually declaring said class.

Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
PeyloW
  • 36,742
  • 12
  • 80
  • 99
9

The angle brackets indicate a protocol. They're analogous to interfaces in other languages.

Charles Holbrow
  • 3,967
  • 6
  • 30
  • 35
philsquared
  • 22,403
  • 12
  • 69
  • 98
6

You can also use them in code like a cast to tell the complier to expect an object that conforms to a particular protocol.

id <NSFetchedResultsSectionInfo> sectionInfo = [[self.noteFetcher sections] objectAtIndex:section];
TechZen
  • 64,370
  • 15
  • 118
  • 145
4

Apple documentation reports the use of brackets; see The Objective-C Programming Language on the chapter 4, on "Adopting a Protocol".

Adopting a protocol is similar in some ways to declaring a superclass. Both assign methods to the class. The superclass declaration assigns it inherited methods; the protocol assigns it methods declared in the protocol list. A class is said to adopt a formal protocol if in its declaration it lists the protocol within angle brackets after the superclass name:

@interface ClassName : ItsSuperclass < protocol list >

Categories adopt protocols in much the same way:

@interface ClassName ( CategoryName ) < protocol list >
apaderno
  • 28,547
  • 16
  • 75
  • 90