Returning/Passing a reference as its protocol
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.
精彩评论