ios常用的三种传值方式

iOS中有多种方案可以实现页面之间的传值,例如:属性传值、代理传值、block传值、单例传值...。常用的三种传值方式就是属性传值、代理传值、block传值。一般属性传值是正向传值。代理和block传值方式多用于反向传值。

1.纯代码方式

  • 属性传值

controller1controller2之间实现属性传值。

controller2 .h文件

#import "ViewController.h"
@interface SecondController : ViewController
@property (strong, nonatomic) NSString *labelStr;
@end 

controller1 .m文件

SecondController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondController"];
controller.labelStr = @"属性传值";//传递给controller2
[self presentViewController:controller animated:YES completion:nil];

这样就利用了属性传值,将controller1中的值传递给了controller2

  • 代理传值

下面利用代理传值的方式,将controller2中的值传递给controller1

controller2 .h文件

#import "ViewController.h"
@protocol SecondControllerDelegate 
- (void)delegateValue:(NSString *)delegateValue;
@end
@interface SecondController : ViewController
@property (weak, nonatomic) iddelegate;
@end

controller2 .m文件

 [self dismissViewControllerAnimated:YES completion:nil];
 if ([self.delegate respondsToSelector:@selector(delegateValue:)]) {
        [self.delegate delegateValue:@"代理传值"];
    }

controller1 .m文件

#import "ViewController.h"
#import "SecondController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *showLabel;
- (IBAction)attributeValueAction:(UIButton *)sender;
@end
@implementation ViewController
- (IBAction)attributeValueAction:(UIButton *)sender {
    SecondController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondController"];
    controller.labelStr = @"属性传值";
    controller.delegate = self;//代理
    [self presentViewController:controller animated:YES completion:nil];    
}
//实现controller2的代理方法
- (void)delegateValue:(NSString *)delegateValue{
    self.showLabel.text = delegateValue;  
}
@end

controller2中定义了一个代理,并给了代理声明了一个方法。然后我们在controller1中遵循controller2的代理,实现controller2的代理方法。

  • block 传值

controller2controller1方向传值还可以用block传值。
controller2中声明一个block类型。

controller2 .h文件

#import "ViewController.h"
/**
 定义一个block
 */
typedef void (^Block) (NSString *strValue);
@interface SecondController : ViewController
@property (copy, nonatomic) Block valueBlock;
@end

controller2 .m文件

 if (self.valueBlock) {
        self.valueBlock(@"Block传值");//传递参数
    }
[self dismissViewControllerAnimated:YES completion:nil];

controller1 中实现controller2中的block方法,接受传递过来的参数。

controller1 .m文件

 SecondController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondController"];
controller.valueBlock = ^(NSString *value){
         self.showLabel.text = value;
    };
    [self presentViewController:controller animated:YES completion:nil];

这样我们就实现了controller1controller2两个页面之间的互相传值。

你可能感兴趣的:(ios常用的三种传值方式)