简体   繁体   中英

Objective-C Protocol Madness — how to return object based on protocol?

@protocol Eating
@end

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

@implementation Eat
- (id<Eating> *)me { return self; }
@end

In the above piece of Objective-C code, why does "return self" result in a "Return from incompatible pointer type" warning? What's the incompatible pointer type and how to fix it?

Because id is a pointer itself, you don't need the asterisk.

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

好的..答案是“id”而不是“id *”。

remove id * and replace with id. id is already a pointer.

Because id is essentially NSObject * (although there are some minor differences). Thus, when you return self , you are returning -(NSObject *) . What you have is id * which is like NSObject ** .

You are slightly off in your use - it's:

- (id<Eating>)me { return self; }

(because you are returning id, not a pointer to an object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM