IOS类与类之间的传值

来源:互联网 发布:最优化文章 编辑:程序博客网 时间:2024/05/18 20:10

类与类之间的传值分为正向和反向,在A中向B传值,B还没创建的情况:
给B中的属性设置值,比如要传值给B的Label,千万不能
B.label.text = name;因为这个时候控制器中的View还没被创建,所以B.Label现在为null。要给先传值给B中的NSString类:B.str = name;然后再在B中self.label.text = self.str;

反向传值A是已经创建了,在B中要传值给A,就不能直接给A中的属性赋值,因为上面的方法先alloc了B的类,如果现在B再alloc一个A的类那么这个A不是原来那个已经存在的A。所以我们采用的方式是用通知或者代理的方法。

通知的方法有一个通知中心,类之间可以通过这个通知中心来互相传值,但这样的问题就是要是通信数据多了类之间耦合度就高了,不推荐,所以这个方法就不记下了。

一般我用的是协议代理的方法。
首先创建一个协议CommitProtocol,在协议中定义一个方法
- (void) labelTextChanged : (NSString *) text;在B中设置代理属性
@property (nonatomic,assign) id < CommitProtocol > delegate;
然后在A中设置B的代理对象为A,B.delegate = self;

上代码:

@interface ViewController ()@property (nonatomic,strong) UILabel *showLabel;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //创建一个Label显示文字    _showLabel = [[UILabel alloc] initWithFrame:CGRectMake((deviceWidth - 200) / 2.0, 100, 200, 100)];    _showLabel.text = @"Hello World!";    _showLabel.textAlignment = NSTextAlignmentCenter;    [self.view addSubview:_showLabel];    //创建一个按钮点击推送到下个页面    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];    [btn setFrame:CGRectMake((deviceWidth - 200) / 2, 200, 200, 100)];    [btn addTarget:self action:@selector(pushToNext) forControlEvents:UIControlEventTouchUpInside];    [btn setTitle:@"下一页" forState:UIControlStateNormal];    [self.view addSubview:btn];    // Do any additional setup after loading the view, typically from a nib.}- (void) pushToNext{    NextViewController *nextVC = [[NextViewController alloc] init];    nextVC.delegate = self;    [self presentViewController:nextVC animated:YES completion:nil];}//通过LabelChanged这个协议的方法在此页面完成nextVC的代理方法- (void) LabelChanged:(NSString *)message{    _showLabel.text = message;}

NextViewController.m中的代码:

//创建一个按钮点击推送到下个页面    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];    [btn setFrame:CGRectMake((deviceWidth - 200) / 2.0, 200, 200, 100)];    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];    [btn setBackgroundColor:[UIColor yellowColor]];    [btn setTitle:@"返回" forState:UIControlStateNormal];    [self.view addSubview:btn];    // Do any additional setup after loading the view from its nib.}//点击按钮当前页面消失并把上个页面的Label的内容设置为_changLabelTextView的内容- (void) back{    [self.delegate LabelChanged:_changLabelTextView.text];    [self dismissViewControllerAnimated:YES completion:nil];}
0 0
原创粉丝点击