开发者

What are the angle brackets "<…>" in an Obj-C class interface for?

开发者 https://www.devze.com 2022-12-14 07:54 出处:网络
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):

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 MapMeViewControlle开发者_StackOverflowr is a CLLocationManagerDelegate, MKReverseGeocoderDelegate, MKMapViewDelegate, or UIAlertViewDelegate

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


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.


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


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];


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 >
0

精彩评论

暂无评论...
验证码 换一张
取 消