Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling optional delegate methods

i created a delegate for a class

@protocol gameDelegate <NSObject>
@optional
-(void)gameStarted;
@required
@end

now in my game object i called this method:

[self.delegate gameStarted];

so now, if i initiate this object anywhere and set the delegate everything works fine until the gameStated gets called, because its not implemented in the main object where the game object is created (because its optional).

i tried some variations of this

if(![self.delegate respondsToSelector: @selector(gameStarted)]) {
    //[self.delegate gameStarted];
}

but this is not working for me. any ideas how to make this "really" optional?

thanks in advance

like image 961
choise Avatar asked Nov 22 '10 22:11

choise


People also ask

How do I make the optional delegate method in Swift?

To define Optional Protocol in swift you should use @objc keyword before Protocol declaration and attribute / method declaration inside that protocol. Below is a sample of Optional Property of a protocol.

What is optional func in Swift?

For pure Swift code, you can instead use a property whose type is the same as the type of the function you want be optional (but wrapped into an Optional ), and assign it to nil in implementing types that you don't want to implement that function (unfortunately, you won't have named arguments and generics).

What is a delegate in Swift programming?

In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object.


1 Answers

Omit the negation from your if statement:

if ([self.delegate respondsToSelector:@selector(gameStarted)]) {
    ...
}
like image 106
Ole Begemann Avatar answered Oct 28 '22 02:10

Ole Begemann