I came from a java background and I was trying to use the protocol as a java interface.
In java, you can implement an object with an interface and pass it to the following method:
public interface MyInterface {
void myMethod();
}
public class MyObject implements MyInterface {
void myMethod() {
}
public class MyFactory {
static void doSomething(MyInterface obj) {
obj.myMethod();
}
}
public void main(String[] args) {
MyInterface obj = new MyObject();
MyFactory.doSomething(obj);
}
I was wondering if it is possible to do the same with objective-c, possibly with a different syntax.
The way I found is to declare a protocol
@protocol MyProtocol
-(NSUInteger)someMethod;
@end
then my object will "accept" this protocol in a specific method that I could write:
-(int) add:(NSObject*)object {
if ([object conformsToProtocol:@protocol(MyProtocol)]) {
[object someMethod];
} else {
}
}
The first question is how to remove the warning, but in any case, the other caller can still pass the wrong object to the class, since the check is performed inside the method. Can you point out some other way?
thanks Leonardo