IOS开发笔记(2)页面之间传递数据几种方式比较

今天分享一下页面之间传值的几种方式

1、@property属性

这个不用多说了吧,当页面A 跳转到页面B,在class B中声明属性

@property (nonatomic, copy) NSString *name;  

初始化B

FirstViewController *firstVC = [FirstViewController new];
firstVC.name = @"name";
[self presentViewController:firstVC animated:YES completion:nil];

2、Delegate

当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个@protocol,并声明属性delegate;

#import <UIKit/UIKit.h>

@protocol FirstViewControllerDelegate <NSObject>

- (void)print;

@end

@interface FirstViewController : UIViewController

@property (nonatomic, assign) id<FirstViewControllerDelegate> delegate;

@end
.m文件
- (void)backClick:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        if ([self.delegate respondsToSelector:@selector(print)]) {
            [self.delegate print];
        }
    }];
}
页面A .m实现,要继承FirstViewController的代理

- (void)buttonClicked:(UIButton *)sender
{
    FirstViewController *firstVC = [FirstViewController new];
    firstVC.delegate = self;
    [self presentViewController:firstVC animated:YES completion:nil];
}

#pragma mark - FirstViewControllerDelegate
- (void)print
{
    NSLog(@"delegate response");
}

3、Block

当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个block,并声明属性block

#import <UIKit/UIKit.h>

typedef void (^FirstViewControllerBlock)(NSString *str);

@interface FirstViewController : UIViewController

@property (nonatomic, copy) FirstViewControllerBlock block;

@end
.m文件

- (void)backClick:(UIButton *)sender
{
    self.block(@"first block");
    [self dismissViewControllerAnimated:YES completion:nil];
}
页面A .m实现

- (void)buttonClicked:(UIButton *)sender
{
    FirstViewController *firstVC = [FirstViewController new];
    [self presentViewController:firstVC animated:YES completion:nil];
    firstVC.block = ^(NSString *str) {
        NSLog(@"str is: %@", str);
    };
}

4、NSNotification

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。