3

Normally when developer makes a pointer to the instance of class which implements a protocol, she does this:

id<ProtocolName> myInstance = [[SomeClass alloc] init];

Is it OK to be more specific about the instance's class type and use it like this?

SomeClass<ProtocolName> *myInstance = [[SomeClass alloc] init];

Or in method:

- (SomeClass<ProtocolName> *)someMethodWithArg:(int)arg;

With implementation (assume SomeSuperClass is superclass of SomeClass):

- (SomeClass<ProtocolName> *)someMethodWithArg:(int)arg
{
   SomeClass<ProtocolName> *instance = [[SomeSuperClass alloc] init];

   return instance;
}
valdyr
  • 198
  • 1
  • 10

1 Answers1

3

Yes, it is OK. (Although I think your last example uses SomeClass where it should be using SomeSuperClass, but I understand what you meant.)

In fact, sometimes you will need to do that. For example, to use autorelease or release on an NSObject (which is not available to an id<ProtocolName> (unless ProtocolName explicitly conforms to the NSObject protocol)), you would have to use:

NSObject<ProtocolName> *protoObj = [....];
[....]
[protoObj autorelease];
Smilin Brian
  • 980
  • 8
  • 18
  • 2
    You can use `id` if your protocol conforms to the `NSObject` protocol. – albertamg Sep 27 '12 at 16:53
  • 2
    `id`, by itself, would match any method anywhere. `id` explicitly limits the namespace to just `Protocol`, which is why you need `SomeClass*` or `id` or declare your protocol to also implement `NSObject`. – bbum Sep 27 '12 at 16:55
  • Thanks for the comments -- those add more explicit details/limitations to my example. Maybe I should have just left it at "Yes it is OK" :-) – Smilin Brian Sep 28 '12 at 16:55