开发者

Returning/Passing a reference as its protocol

开发者_StackOverflow社区

Given

@protocol Person<NSObject>

@interface Greek : NSObject <Person> 

Can you define a method as

+(id<Person>)newGreek{
return [[Greek alloc] init];        
}

and use the return type as

id<Person> person = [Persons newGreek];

Or call a method

Greek *greek = [[Greek alloc] init];
[self talk:greek];

which is defined as

-(void)talk:(id<Person>)person

If not, what are the alternatives?


Yes you can. In Protocols in the Objective-C Programming Language, the section on Type Checking specifically shows the first form, and the second works as well, even though it is not listed on that page. The protocol declaration (<Person>) is a type modifier which can be used on any objective-c object, meaning you can use it wherever you define the type of the object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜