I came from a java background, and I was trying to use protocol like a java interface.
In java you can have an object implement an interface and pass it to a method like this:
public interface MyInterface {
void myMethod();
}
public class MyObject implements MyInterface {
void myMethod() {// operations}
}
public class MyFactory {
static void doSomething(MyInterface obj) {
obj.myMethod();
}
}
public void main(String[] args) {
// get instance of MyInterface from a given factory
MyInterface obj = new MyObject();
// call method
MyFactory.doSomething(obj);
}
I was wondering if it’s possible to do the same with objective-c, maybe with other syntax.
The way I found is to declare a protocol
@protocol MyProtocol
-(NSUInteger)someMethod;
@end
then my object would “adopt” that protocol and in a specific method I could write:
-(int) add:(NSObject*)object {
if ([object conformsToProtocol:@protocol(MyProtocol)]) {
// I get a warning
[object someMethod];
} else {
// other staff
}
}
The first question would be how to remove the warning, but then in any case other caller could still pass wrong object to the class, since the check is done inside method.
Can you point out some other possible way for this ?
thanks
Leonardo
You can make the compiler do the (static) checking for you. Change you method signature to:
That tells the compiler, that
objectcan be of any class that conforms toMyProtocol. It will now warn you, if you try to calladd:with an object of a class that does not conform.Edit:
To make usage of objects that conform to
MyProtocoleasier, it’s helpful letMyProtocolextend NSObject:Now you can send messages like
retain,releaseorrespondsToSelector:to objects with a static type ofid <MyProtocol>Especially the last is helpful in cases where you use the
@optionalkeyword in the protocol.