Search code examples
iosobjective-cadapterdelegation

Cant call delegate method from my protocol class


I have a protocol in one class:

@protocol DataStorageManager

- (void) saveFile;

@end

@interface DataManager : NSObject
{
    id <DataStorageManager> delegate;
}

@property (nonatomic, assign) id<DataStorageManager> delegate;

//methods

@end

and its implementation:

@implementation DataManager

@synthesize delegate;

@end

and I have another class which is the adapter between the first and the third one:

#import "DataManager.h"
#import "DataPlistManager.h"

@interface DataAdapter : NSObject <DataStorageManager>

@property (nonatomic,strong) DataPlistManager *plistManager;
- (void) saveFile;

@end

and its implementation

#import "DataAdapter.h"

@implementation DataAdapter

-(id) initWithDataPlistManager:(DataPlistManager *) manager
{
    self = [super init];
    self.plistManager = manager;
    return self;
}

- (void) saveFile
{
    [self.plistManager savePlist];
}

@end

So when I in first method try to call my delegate method like this

[delegate saveFile]; 

Nothing happened. I don't understand what's wrong with the realization - it's a simple adapter pattern realization. So I need to use the delegate which will call the methods from the third class. Any help?


Solution

  • You are not setting the delegate property. You need to do this,

    -(id) initWithDataPlistManager:(DataPlistManager *) manager
    {
        self = [super init];
        self.plistManager = manager;
        self.plistManager.delegate = self;
        return self;
    }
    

    Also, in DataManager class remove the ivar declaration, just declaring property is sufficient, the ivar gets automatically created. Call the delegate method as below,

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

    Hope that helps!