Objective-C Protocol Madness - 如何根据协议返回对象?

me2*_*me2 11 iphone protocols objective-c

@protocol Eating
@end

@interface Eat : NSObject<Eating>
{
}
- (id<Eating> *)me;
@end

@implementation Eat
- (id<Eating> *)me { return self; }
@end
Run Code Online (Sandbox Code Playgroud)

在上面的Objective-C代码中,为什么"返回self"导致"从不兼容的指针类型返回"警告?什么是不兼容的指针类型以及如何解决它?

Geo*_*lly 14

因为id是指针本身,所以不需要星号.

@interface Eat : NSObject<Eating> {
}
- (id<Eating>)me;
@end
Run Code Online (Sandbox Code Playgroud)

  • 这是一个星号,而不是Asterix:http://en.wikipedia.org/wiki/Asterix;)(我花了三次才得到这个评论!) (2认同)