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:Incidentally, you have created your delegate property using
strong
semantics. Unless you have a particularly good reason to usestrong
, delegates should beweak
, since yourBrain
class doesn't own its delegate (if you think about the object graph).