views:

504

answers:

2

Are these basically the same thing?

For example if I have an interface in Java

public interface CoolObject{
 ...
}

I can use any object that implements the CoolObject interface in functions that take a CoolObject as a parameter:

public void foo(CoolObject o) {
...
}

Is this the same in Objective-C?

@protocol CoolProtocol
...
@end

@interface Foo: NSObject <CoolProtocol>
...
@end

(void) - someMethod: (CoolProtocol *) obj {
}

Would the above work (and be considered correct?)

Thanks for your time. Let me know if you need me to clarify my question.

+7  A: 

Close. In Objective C, you indicate that an object implements a protocol with angle brackets <>, so you would write your method like one of these:

- (void) someMethod: (id <CoolProtocol>) obj { }
- (void) someMethod: (id <NSObject, CoolProtocol>) obj { }
- (void) someMethod: (NSObject <CoolProtocol> *) obj { }

In all cases, you are saying that someMethod requires an object that implements CoolProtocol.

id is a generic pointer to any kind of Objective C object.

So id < CoolProtocol> means "Any kind of objective C object that implements CoolProtocol.

Often, you want to be able to retain/release/autorelease the object, and generally treat it like a regular Cocoa object, so it is often good to add the NSObject protocol as well, which is what the second case does.

And if you want to ensure it actually is a proper Cocoa object (excluding NSProxy based objects), then you can use the last form, which says basically "I want any kind of real Cocoa Objective C object that implements CoolProtocol.

Peter N Lewis
Good answer. A related approach is to have CoolProtocol adopt the NSObject protocol, which makes id <CoolProtocol> work just fine. The last form is correct, but usually overly verbose since objects that (unintentionally) fail to subclass NSObject generally cause errors at compile time, and it invokes static typing which reduces the dynamism which makes Objective-C so powerful and flexible.
Quinn Taylor
+1  A: 

Peters answer is great. I would like to add one thing though. If you add the "NSObject" protocol to your protocol

@protocol CoolProtocol <NSObject>
@end

This would alleviate the need to for you to declare the NSObject protocol in the method declaration.

- (void) someMethod: (id <NSObject, CoolProtocol>) obj { }

Now becomes

 - (void) someMethod: (id <CoolProtocol>) obj { }