What are the angle brackets “<…>” in an Obj-C c

2020-08-09 06:26发布

Can anyone tell me what the angle brackets "<…>" in an Obj-C class interface do? Like this… 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.

4条回答
成全新的幸福
2楼-- · 2020-08-09 07:07

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.

查看更多
虎瘦雄心在
3楼-- · 2020-08-09 07:14

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

查看更多
贼婆χ
4楼-- · 2020-08-09 07:15

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 >
查看更多
Juvenile、少年°
5楼-- · 2020-08-09 07:21

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];
查看更多
登录 后发表回答