Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a controller conforms to a protocol then is it necessary for it to provide a body to all the methods of protocol?

In Java, there is wrapper classes. but in objective c what is there any wrapper class or something else?

like image 669
Nick Avatar asked Dec 31 '25 05:12

Nick


2 Answers

In ObjectiveC protocol methods can be marked as @optional - those ones don't have to be implemented. e.g.

@protocol MyProtocol <NSObject>

@required

- (NSUInteger) methodOne;

@optional

- (NSUInteger) methodTwo; // Doesn't have to be implemented

@end

The method that calls the protocol should then check to see if the instance responds to that selector:

if ([anInstanceOfAClassThatImplementsMyProtocol respondsToSelector:@selector( )]) {
        [myProtocolInstance methodTwo];
    }
like image 56
tarmes Avatar answered Jan 02 '26 19:01

tarmes


You wil get a warning if you dont implement obligatory methods in the protocol. A protocol is typically defined like this:

@protocol SomeProtocol<NSObject>
- (void)obligatoryMethod;
@optional
- (void)optionalMethod;
@end
like image 45
Thomas Johan Eggum Avatar answered Jan 02 '26 17:01

Thomas Johan Eggum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!