Question

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?

Was it helpful?

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!

OTHER TIPS

In your case you forget to set your protocol delegate and also need to call protocol method
by self.delegate....

I just Give Basic Idea for how to Create Protocol

Also Read This Question

#DetailViewController.h

#import <UIKit/UIKit.h>

@protocol MasterDelegate <NSObject>
-(void) getButtonTitile:(NSString *)btnTitle;
@end


@interface DetailViewController : MasterViewController

@property (nonatomic, assign) id<MasterDelegate> customDelegate; 

#DetailViewController.m

if([self.customDelegate respondsToSelector:@selector(getButtonTitile:)])
{
          [self.customDelegate getButtonTitile:button.currentTitle];    
}

#MasterViewController.m

create obj of DetailViewController

DetailViewController *obj = [[DetailViewController alloc] init];
obj.customDelegate = self;
[self.navigationController pushViewController:reportTypeVC animated:YES];

and add delegate method in MasterViewController.m for get button title.

#pragma mark -
#pragma mark - Custom Delegate  Method

-(void) getButtonTitile:(NSString *)btnTitle;
{
    NSLog(@"%@", btnTitle);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top