0

Please tell the where is the error in this code.I don't want to call the method myMethodToDoStuff. Is there any other way it will work ?

MyClass.h file should look like this (add delegate lines with comments!)

#import <BlaClass/BlaClass.h>

@class MyClass;             //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject>   //define delegate protocol
    - (void) myClassDelegateMethod: (MyClass *) sender;  //define delegate method to be implemented within another class
@end //end protocol

@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate

@end

MyClass.m file should look like this

#import "MyClass.h"
@implementation MyClass 
@synthesize delegate; //synthesise  MyClassDelegate delegate

- (void) myMethodToDoStuff {
    [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
}

@end

To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:

#import "MyClass.h"
@interface MyVC:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}

MyVC.m:

myClass.delegate = self;          //set its delegate to self somewhere

Implement delegate method

- (void) myClassDelegateMethod: (MyClass *) sender {
    NSLog(@"Delegates are great!");
}

1 Answers1

0

There doesn't appear to be any error - this is a correct implementation of a delegate. In order to get myClassDelegateMethod: called, something inside MyClass will need to call myMethodToDoStuff. You could, for example, create another method that is publicly accessible, which calls myMethodToDoStuff. Then this method can be called in MyVC.

@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate

- (void) someOtherMethod;

@end

And in MyClass.m

#import "MyClass.h"
@implementation MyClass 
@synthesize delegate; //synthesise  MyClassDelegate delegate

 - (void) myMethodToDoStuff {
    [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
}

 - (void) someOtherMethod {
     [self myMethodToDoStuff];
 }

@end

And finally in MyVC:

myClass.delegate = self;          //set its delegate to self somewhere
[myClass someOtherMethod];
Allan Poole
  • 377
  • 1
  • 10