美文网首页项目可能用程序员@IT·互联网
iOS中页面间常用四种传值方式:通知,委托,block,单例

iOS中页面间常用四种传值方式:通知,委托,block,单例

作者: 小菜鸟爱开发 | 来源:发表于2016-03-23 15:43 被阅读350次

1、通知

在传值的地方写:

//    创建通知对象

NSString *str = @"通知";

NSNotification *note = [[NSNotification alloc] initWithName:@"TextValueChanged" object:str userInfo:nil];

//  通过通知中心发送通知

[[NSNotificationCenter defaultCenter] postNotification:note];

接收的地方写:

//    接收通知

//    向通知中心注册一个新的观察者(第一个参数)

//    第二个参数是收到通知后需要调用的方法

//    第三个参数是要接收得通知的名字

//    第四个参数通知是nil,表示不管哪个对象发送通知都要接收

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noteReceived:) name:@"TextValueChanged" object:nil];

-(void)noteReceived:(NSNotification *)note

{

UILabel *label = (UILabel *)[self.view viewWithTag:1000];

NSString *str = note.object;

label.text = str;

}

//释放数据防止通知泄露,去掉通知

-(void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

2、委托回调

先建一个Protocol文件

申明委托的方法

在传值类的.h中写

#import <UIKit/UIKit.h>

#import "CDChangeValueDelegate.h"

@interface SecondViewController : UIViewController

@property (nonatomic,strong) id<CDChangeValueDelegate>delegate;

@end

.m中要传值的位置写

NSString *str = @"委托";

[self.delegate changeValue:str];

在接收地方写(记得要写代理)

3、block传值

在要传值类的.h中申明block

#import <UIKit/UIKit.h>

typedef void (^CDMyBlockType)(NSString *);

@interface SecondViewController : UIViewController

//用一个属性来接收block表达式

@property (nonatomic,copy) CDMyBlockType block;

@end

传值.m中写

//  传送block的参数

NSString *str = @"Block";

self.block(str);

在接收地方写

SecondViewController *second = [[SecondViewController alloc] init];

//    接收block传的值

second.block = ^(NSString *str)

{

UILabel *label =(id)[self.view viewWithTag:1000];

label.text = str;

};

4、单例传值

首先建一个类Appstorage

 

在传值地方进行赋值

NSString *str = @"单例";

[AppStorage sharedInstance].str = str;

在接收地方写

UILabel *label = (UILabel *)[self.view viewWithTag:1000];

if ([AppStorage sharedInstance].str) {

label.text = [AppStorage sharedInstance].str;

}

相关文章

网友评论

    本文标题:iOS中页面间常用四种传值方式:通知,委托,block,单例

    本文链接:https://www.haomeiwen.com/subject/dfgllttx.html