我的实验步骤是创建带一个视图的项目,
默认的第一个视图的名称为ViewController
新建一个SecondViewController
第一步 在SecondViewController中声明一个协议,并写一个协议方法,然后在这个类中写一个属性,代码如下:
#import <UIKit/UIKit.h>
// MyDelegate Start
@protocol MyDelegate <NSObject>
- (void)showMessage; //协议方法
@end
// MyDelegate End
@interface SecondViewController : UIViewController
@property(nonatomic, weak)id<MyDelegate> delegate; // 此对象的一个属性
@end
第二步 在SecondViewController.m中写一下delegate这个属性的set方法 ,然后在set方法 里面去实现调用协议中的方法,代码如下:
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
// delegate 的 set 方法
- (void)setDelegate:(id<MyDelegate>)delegate{
NSLog(@"delegate = %@", delegate);
NSLog(@"_delegate = %@", _delegate);
// _delegate = delegate; // 直接给_delegate赋值,最好用下面三行代替,判断一下是否相同,只有在两个对象不相同的时候才赋值
if (_delegate != delegate) {
_delegate = delegate;
}
//此处回调一下,到这里就完,这里相当于调用了实现该协议的那个对象的方法,称为回调,系统里面有TableView等等,这是IOS中的一个经典的设计模式,所以今天搞懂了一下
[self.delegate showMessage];
}
@end
第三步 在ViewController中声明实现 MyDelegate这个协议,代码如下:
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface ViewController : UIViewController<MyDelegate> // 此类实现 MyDelegate 协议
@end
第四步 创建SecondViewController对象,给对象的delegate赋值
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *svc = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil]; // 创建SecondViewController
svc.delegate = self; // 设置 SecondViewController 的代理属性为当前对象,这里是给 svc的delegate属性赋值,会自动执行 svc中的setDelegate方法,然后我们在 svc里面写上一个setDelegate方法,里面实现回调
}
- (void)showMessage{
NSLog(@"I execute delegate");
}
@end