@protocol is not working

0

I'm implementing a protocol but the same is not able to call the delegate :

if ([self.delegate respondsToSelector:@selector(addCard)]) {
    [self.delegate addCard];
}

ViewController.m

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>


@protocol ViewControllerDelegate <NSObject>

-(void)addCard;
@end


@interface ViewController : UIViewController{
}

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


- (IBAction)setCard:(id)sender;

@end




#import "ViewController.h"
#import "PSWallet.h"


@interface ViewController ()

@end

@implementation ViewController
@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



- (IBAction)setCard:(id)sender {

    if ([self.delegate respondsToSelector:@selector(addCard)]) {
        [self.delegate addCard];
    }
}
@end

PSWallet.m

#import <Foundation/Foundation.h>
#import "ViewController.h"


@interface PSWallet : NSObject<ViewControllerDelegate>

@end


#import "PSWallet.h"


@interface PSWallet ()

@end

@implementation PSWallet

-(void)addCard{


    NSLog(@"not work");
}

@end
    
asked by anonymous 21.09.2016 / 04:45

1 answer

0

Its delegate is a id<ViewControllerDelegate> and in the protocol definition ViewControllerDelegate the addCard method is not optional. Therefore%% checking is theoretically unnecessary.

Your code should work. Are you setting [self.delegate respondsToSelector:@selector(addCard)] to delegate ? Is there at least a ViewController reference to it?

Your code compiles and works fine here by setting strong .

    
21.09.2016 / 07:09