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