Hi all,
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