代理传值

如果您在阅读我的文章时有疑问 , 请点击这里

  • 首先有两个ViewController , 实现两个界面
  • 在第二个界面的 .h 里面 写协议方法 和定义协议
//协议方法
@class AddViewController;
@protocol   AddViewControllerDelegate <NSObject>
@optional
-(void)addViewController:(AddViewController *)addViewController withTeacher :(Teacher *)teacher;
@end
@interface AddViewController : UIViewController
//定义协议
@property (nonatomic,strong)id<AddViewControllerDelegate> delegate;
@end
  • 在第二界面的 .m 需要传值的地方
-(void)addclick{
    [self.navigationController popViewControllerAnimated:YES];
    //判断代理方法是否响应
    if ([self.delegate respondsToSelector:@selector(addViewController:withTeacher:)]) {
        //执行代理方法
        Teacher *t=[Teacher new];
        t.name=self.nameField.text;
        t.number=self.numberField.text;
        [self.delegate addViewController:self withTeacher:t];
    }
}
  • 返回到第一界面 , 写代理
@interface ViewController ()<AddViewControllerDelegate,EditViewControllerDelegate>
  • 代理方法
//代理方法
-(void)addViewController:(AddViewController *)addViewController withTeacher:(Teacher *)teacher{
    [self.array addObject:teacher];
    NSLog(@"%@",teacher.name);
    [table reloadData];
   //归档
    [NSKeyedArchiver archiveRootObject:_array toFile:Kfilepath];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。