1.在iOS中正向傳值 可以用屬性就不多說了,反向傳值 從image中傳值給controller的時候 我們可以用 代理 Block代碼塊 還有通知的方法傳值
舉個例子: A頁面push到B頁面 現(xiàn)在要從B頁面pop回 A頁面的時候傳值給 A頁面
(1).簡單說就是從B頁面?zhèn)髦到oA頁面
可以用block傳值
在B頁面的.h中聲明block的函數(shù)
block的聲明
@1. typedef void(^block函數(shù)名)(參數(shù)名);
@2. 聲明block的屬性 用copy 在ARC中用strong也可以 不過蘋果官方建議用copy
@3. 為了防止循環(huán)引用 在block的 賦值方法中 要用weakself 弱引用
typedef void(^SelectedBlock)(NSString *textname);
@interface textTwoVC : UIViewController
@property (nonatomic, copy) SelectedBlock selectedBlock;
typedef void 是聲明一個新的類型 SelectedBlock 是block函數(shù)的名字 textname 是傳值的內(nèi)容 當(dāng)然可以傳遞多個參數(shù)
(2)然后在B頁面的.m中 進(jìn)行傳值操作
if (self.selectedBlock) {
self.selectedBlock(@"傳值123");
}
判斷一個block是否存在 在進(jìn)行傳值
(3)在A頁面中接受B頁面?zhèn)鬟^來的值 在A頁面需要取值的時候
_texttwoVC.selectedBlock=^(NSString *textStr){
//textStr 就是傳過來的值
};
2.通過通知傳值
大體的套路和block差不多 就是創(chuàng)建通知中心 進(jìn)行通知傳值 接收通知傳來的值
(1)
//獲取通知中心單例對象
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//添加當(dāng)前類對象為一個觀察者,name和object設(shè)置為nil,表示接收一切通知 給object設(shè)置名字 只接受和object名字匹配的通知消息
[center addObserver:self selector:@selector(notice:) name:@"ceshi" object:nil];
(2)
//創(chuàng)建一個消息對象
NSNotification * notice = [NSNotification notificationWithName:@"ceshi" object:nil userInfo:@{@"1":@"123"}];
//發(fā)送消息
[[NSNotificationCenter defaultCenter]postNotification:notice];
(3)
//在回調(diào)的函數(shù)中取出通知的值
-(void)notice:(id)sender{
NSLog(@"%@",sender);
}