是的,您可以为此使用委托。
例如,你可能有这个 ViewControllers。
//FirstViewController.h
@protocol ProtocolName <NSObject>
- (void)doSomething;
@end
@interface FirstViewController
@property (nonatomic, strong) id<ProtocolName> delegate;
@property (weak, nonatomic) IBOutlet UIButton *button;
- (IBAction)action:(id)sender;
@end
这里我们需要一个协议,它定义了一个或多个要在任何实现该协议的对象中实现的方法。而且我们还需要一个委托,即实现此协议的对象(在本例中称为“ProtocolName”,但您可以随意命名)。
然后是第二个 ViewController
//SecondViewController.h
#import "FirstViewController.h" //Need this to reference protocol
@interface SecondViewController <ProtocolName>
@end
我们说 SecondViewController 将实现 ProtocolName 协议,所以在他的 .m 文件中我们需要这样做。
//SecondViewController.m
- (void)doSomething{
//Do something
}
魔法来了。
假设当您点击 FirstViewController 中的按钮时,它会触发 SecondViewController 中的 doSomething 方法。所以,你需要做这样的事情。
//FirstViewController.m
//...
SecondViewController secondVC = [[SecondViewController alloc] init];
this.delegate = secondVC; //DON'T FORGET THIS
//...
- (IBAction)action:(id)sender{
[this.delegate doSomething];
}
这就是委托模式。