下面的代码只是展示了委托概念的基本用法。您可以根据需要命名变量和类。
首先你需要声明一个协议:
我们称之为MyFirstControllerDelegate.h
@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end
导入 MyFirstControllerDelegate.h 文件并使用协议 MyFirstControllerDelegate
确认您的
FirstController
#import "MyFirstControllerDelegate.h"
@interface FirstController : UIViewController<MyFirstControllerDelegate>
{
}
@end
在实现文件中,需要实现protocol的两个功能:
@implementation FirstController
- (void) FunctionOne: (MyDataOne*) dataOne
{
//Put your finction code here
}
- (void) FunctionTwo: (MyDatatwo*) dataTwo
{
//Put your finction code here
}
//Call below function from your code
-(void) CreateSecondController
{
SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
//..... push second controller into navigation stack
mySecondController.delegate = self ;
[mySecondController release];
}
@end
在您的 SecondController 中:
@interface SecondController:<UIViewController>
{
id <MyFirstControllerDelegate> delegate;
}
@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;
@end
在SecondController的实现文件中。
@implementation SecondController
@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
[delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
[delegate FunctionTwo:myDataSecond];
}
@end
Here 是关于委托的维基文章。