2

I just wanna avoid warning (without compiler suppression), but don't wanna add some includes to my file. Here is my code:

@protocol MyProto;

// ...

Protocol *p = @protocol(MyProto);

Here is warning I got:

@protocol is using a forward protocol declaration of MyProto [-Wat-protocol]
k06a
  • 17,755
  • 10
  • 70
  • 110
  • 1
    No choice. You can't use a type in code before you've defined the type. This applies to classes too. – Avi Mar 28 '16 at 07:32
  • @Avi looks like `Protocol *p` will be nil in case protocol `MyProto` will not exists in runtime? Maybe this is what warning message about? – k06a Mar 28 '16 at 07:58
  • No. The warning means what it says it means. You are using a type before defining it. The compiler is warning you that it can't type-check your usage of the protocol because it doesn't know what the protocol contains. – Avi Mar 28 '16 at 08:09
  • @Avi But I am using this `Protocol *p` only for direct comparison with other protocols like this: `if ([someProtocolsArray containsObject:p]) { ... }` – k06a Mar 28 '16 at 11:02
  • The compiler isn't a prophet. It's warning you that you're using a type that isn't yet defined at the point the compiler sees the usage. If you know it's fine, it's fine. If you really want to suppress the warning, do it right, or manually suppress it using a pragma. Using the pragma is your way of telling the compiler that you know what you're doing and not to bother you. – Avi Mar 28 '16 at 11:06

1 Answers1

1

Using a protocol literal (@protocol) requires linking to the protocol at compile time, which requires the compiler to see the definition of the protocol.

I don't understand why you are averse to "add some includes to my file". It's very normal to include header files defining something in an implementation file that is using that thing. There should be no downside.

If you want to look up the protocol at runtime from a string you can do something like NSProtocolFromString(@"MyProto").

newacct
  • 119,665
  • 29
  • 163
  • 224