请告知此代码中的错误在哪里。我不想调用方法myMethodToDoStuff。还有其他方法吗?
MyClass.h文件应如下所示(添加带注释的委托行!)
#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文件应如下所示
#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
在另一个类中使用你的委托(在这种情况下称为MyVC的UIViewController)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
实施委托方法
- (void) myClassDelegateMethod: (MyClass *) sender {
NSLog(@"Delegates are great!");
}
答案 0 :(得分:0)
似乎没有任何错误 - 这是委托的正确实现。为了调用myClassDelegateMethod:
,MyClass中的某些内容需要调用myMethodToDoStuff
。例如,您可以创建另一个可公开访问的方法,该方法调用myMethodToDoStuff
。然后可以在MyVC中调用此方法。
@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate
- (void) someOtherMethod;
@end
在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
最后在MyVC中:
myClass.delegate = self; //set its delegate to self somewhere
[myClass someOtherMethod];