I created a protocol and assigned it to a delegate object
@protocol AppBrainDelegate <NSObject>
@optional
- (void)didLocateUser;
- (void)didFinishLoadingDataWithData:(NSDictionary *)fetchedData;
@end
@interface Brain : NSObject
@property (strong, nonatomic) id <AppBrainDelegate> delegate;
I thought the meaning of this @optional in the protocol declaration means, that controllers don't have to listen to the delegate method if they don't want to.
Here's the crash log if do not implement the first of the delegate methods in the controller. If I do, I don't crash. Seems like I did not understand the concept of declaring delegate methods as optional. Can you explain to me where my mistake is?
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[EventViewController didLocateUser]: unrecognized selector sent to instance 0x1fb300'
The @optional
simply suppresses a compiler warning if the method is not implemented in a class that conforms to the protocol. Before calling the delegate method, you still need to check that the delegate implements it:
if ([delegate respondsToSelector:@selector(didLocateUser)]) {
[delegate didLocateUser];
}
Incidentally, you have created your delegate property using strong
semantics. Unless you have a particularly good reason to use strong
, delegates should be weak
, since your Brain
class doesn't own its delegate (if you think about the object graph).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With