开发者

Why am I getting a compile error when I return a pointer to a Protocol?

开发者 https://www.devze.com 2023-01-11 09:06 出处:网络
@protocol Runnable - (id<Runnable>) works; //this compiles fine - (Runnable *) broke; // get a compile error saying Expected \')\' before \'Runnable\'
@protocol Runnable

- (id<Runnable>) works; //this compiles fine

- (Runnable *) broke; // get a compile error saying Expected ')' before 'Runnable'

@end

I'm not sure I understand 开发者_运维问答why xCode complains about the - (Runnable *) broke; line


Protocols in Obj-C don't look syntactically like, say, "interfaces" in Java, where the syntax for interface pointers and subclass pointers are essentially the same.

The id<Runnable> is the idiomatic way that you say "an object that conforms to Runnable. An id is a reference to any type of object, and the < > notation expresses an explicit conformance to a given protocol for the purposes of type checking.

If you say Foo *, you're referring to an object of either type Foo or one of its subclasses.

This just happens to be the Obj-C syntax for this. With this syntax, the semantics are similar to what you'd get in, e.g. Java.

0

精彩评论

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