关于iOS传值
2016-11-12 本文已影响192人
noprkl
在iOS开发中有4中传值方式,分别为block
、通知
、代理
、tag-action
,四种方式各有优劣,在通常情况下,可以使用任意的方式来传值,但是在某种环境下只能使用某一种传值方式。
1、使用通知来传值
通知有两种写法NSNotification
(通知中心)和KVO(Key-Value-Observes)
(键值观察)。
使用
NSNOtification
需要先注册观察者,当观察到某件事达到预定的事件,观察者通知通知中心,通知中心来告诉所有的接收者,这个通知是全局量,所以任何类都可能接收到,在通知的 时候把值传过去。
KVO
是通过监听类的属性值的变化来实现某种需求,是基于KVC
的一种通知模式。但是KVO
不能传值。
通知传值
// 在通知中心注册监听者
NSNotification* notification = [NSNotification notificationWithName:@"注册通知中心的标示" object:@"需要传的值"];
[[NSNotificationCenter defaultCenter] postNotification:notification];
// 在需要的地方接收通知的信息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testNSNotification:) name:@"注册通知中心的标示" object:nil];
// 接收到消息后执行的方法
- (void)testNSNotification:(NSNotification *)notification {
NSLog(@"%@",notification.userInfo[@""]);
}
2、block
传值
block
在iOS中又被称为闭包,是一种非常方便的封存代码块的方式。block
是我最常用的方式,写起来方便,调用也很简单。可以传值,控件,方法等等。
// 定义block类型 (A.h文件中)
typedef NSStrig (^FunctionBlock) (NSString *test);
// 返回值类型(可以为void) block类型名字 参数名字(可以包含多个,以,分开)
// 声明一个block属性 (A.h文件中)
@property (strong,nonatomic) FunctionNameBlock funBlock;
// 在需要的地方实现block(A.m文件中)
if (_funBlock) {
NSString *reture = _funBlock(@"传的值");
NSLog(@"%@", reture);
}
// block的调用:在别的类中,如果调用了含有block的这个类,用类对象调用block(B.m文件中)
A *a;
a. funBlock = ^(NSString *test){
// block执行的方法
NSLog(@"%@", test);
reture @"return";
};
3.代理(Protocol
传值)
代理传值就是通过委托代理模式来传递值,即A
定义一个c
协议,委托B
来实现,B
如果能够准守c
协议,B执行c
中的方法,否则没法完成委托。
<big>废话不说上代码</big>
// 定义一个协议 (C.h文件下)
@protocol ProtocolDelegate <NSObject>
// @required 必须实现的方法 (默认)
// @optional 可选实现的方法
- (void)IWantUseProtocol:(NSString *)test;
@end
// 委托方
// 定义一个代理属性(A.h)
@property(nonatomic, weak) id<ProtocolDelegate> deleGate; /**< 定义代理属性用weak修饰 */
// 判断是否能够遵守协议 (A.m)
// 导入文件C.h
if ([self.deleGate respondsToSelector:@selector(IWantUseProtocol:)]) {
[self.deleGate IWantUseProtocol:@"传的值"];
}
// 代理方
// 遵守ProtocolDelegate
#import "B.h"
#import "C.h"
@interface C ()<ProtocolDelegate>
// 如果遵守了`C`协议,用A类对象设置代理(B.m)
A *a;
a.deleGate = self;
// B执行C协议方法
- (void)IWantUseProtocol:(NSString *)test {
NSLog(@"%@", test);
}
4、tag-action
传值
这个是通过检索所有的控件的tag来找到合适对象执行方法,同时把值传过去。
// 最简单的UIButton
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
- (void)clickButton:(UIButton *)btn {
NSLog(@"点击按钮执行事件");
}
// 或者
[self performSelector:@selector(testWithObiect:) withObject:@"传递的值"]
- (void)testWithObiect:(id)object {
NSLog(@"%@", object);
}
5、其他传值方式
iOS传值方式还有其他的,比如控制器之间跳转传值,通过storyboard的标示跳转时执行- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender;
进行传值,不太常用。
<big>一个iOS学习路上的小学僧,欢迎指正!