Alex
Alex

Reputation: 145

Objective C delegate method

a quick question. When design a delegate, if there is any optional delegate method, should I always use the following code to check if the delegate conforms the method?

if ([self.delegate respondsToSelector:@selector(changeBackgroundColor:number:)]) {
    [self.delegate changeBackgroundColor:self number:aNumber];
}

Upvotes: 0

Views: 87

Answers (3)

ninjaproger
ninjaproger

Reputation: 2044

If you declare your delegate like:

@property (weak, nonatomic) id <YourDelegateProtocol> delegate;

and your YourDelegateProtocol has no optional methods, there is no need to check for responding selector. In case when your delegate's class hasn't implement all of YourDelegateProtocol methods, compiler will show error. You should make check for responding selector only for optional methods of the protocol.

Upvotes: 0

Fogh
Fogh

Reputation: 1305

You should always do that, yes. Especially when you have optional delegate methods.

Upvotes: 0

Alexander
Alexander

Reputation: 8147

It's recommended since you're risking to invoke a nonexisting selector.

Upvotes: 1

Related Questions