iOS pop使用代理传值

假如oneViewController页面push到OtherViewController页面,然后你想从OtherViewController页面pop到oneViewController页面的时候需要传值,这时可以使用代理。

从OtherViewController中.h文件中定义代理,并设置代理属性,代码如下

#import <UIKit/UIKit.h>
@protocol OneDelegate
- (void)returnName:(NSString *)name;
@end

@interface OtherViewController : UIViewController
@property (nonatomic, retain) id <OtherDelegate> delegate;
@end

 然后在.m文件中,设置Other控制器的代理是One控制器,这里我们在自定义的pop事件中设置代理

- (void)pop {

    OneViewController *VC = [[OneViewController alloc]init];
    self.delegate = VC;
    [self.delegate returnName:@"名字"];
    [self.navigationController popViewControllerAnimated:YES];
}

然后在oneViewController中,遵循代理,并且实现代理所必须的方法,同时把接收到的值,保存在自己的属性中

@interface OneViewController () <OtherDelegate>
@property (nonatomic, copy) NSString *name;
@end

//所需要实现的代理方法 - (void)returnName:(NSString *)name { self.name = name; NSLog(@"代理收到名字 %@",self.name); }
原文地址:https://www.cnblogs.com/funny11/p/5366238.html