Objective-C. Can you use protocol like a Java interface?
java, objective-c
Solution
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".
Problem
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.