Simulate an interface in java using objective-c

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() {// 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 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)]) {
   // I get a warning
   [object someMethod];
 } else {
   // other staff
 }
}

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

+3
1

() . :

-(int) add:(id<MyProtocol>)object

, object , MyProtocol. , add: , .

Edit:

, MyProtocol, , MyProtocol NSObject:

@protocol MyProtocol <NSObject>
...
@end

retain, release respondsToSelector: id <MyProtocol>

, @optional .

+4

Source: https://habr.com/ru/post/1754096/


All Articles