iOS中頁面間常用四種傳值方式:通知,委托,block,單例

1、通知

在傳值的地方寫:

//? ? 創(chuàng)建通知對象

NSString *str = @"通知";

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

//? 通過通知中心發(fā)送通知

[[NSNotificationCenter defaultCenter] postNotification:note];

接收的地方寫:

//? ? 接收通知

//? ? 向通知中心注冊一個新的觀察者(第一個參數(shù))

//? ? 第二個參數(shù)是收到通知后需要調(diào)用的方法

//? ? 第三個參數(shù)是要接收得通知的名字

//? ? 第四個參數(shù)通知是nil,表示不管哪個對象發(fā)送通知都要接收

[[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;

}

//釋放數(shù)據(jù)防止通知泄露,去掉通知

-(void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}


2、委托回調(diào)

先建一個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的參數(shù)

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;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容