大家好,今天又去复习了一下几个传值的方式,属性传值,代理传值,代码块传值,通知传值.目前常用的四种传值方式
首先是属性传值方式: 属性传值方式使用起来非常简单方便,我们只需要在push到下一个类的时候去给一下个类的属性
代码示例:
- (void)pushToNextView
{
SecondViewController *nextViewController = [[SecondViewControlleralloc] init];
nextViewController.transformString =@"我传值了哦!";
[self.navigationControllerpushViewController:nextViewControlleranimated:YES];
}
这里是传入下一个页面的数值的方法,这里需要提前在第二页的ViewController的.h中定义好属性,就可以接收到属性了,但是属性传值只能向下传值.没有办法想上页面传值;第二:代理传值,代理传值是非常方便的属性传值,可以无视界面就可以将想传出去的内容传递出去,代理传值非常适合穿出单一模式的内容
代码示例:我们要先定义代理
@class ViewController;
@protocol ViewControllerDelegate <NSObject>
- (void)transform:(NSString *)transform;
@end
然后我们要声明属性,为修饰为weak
@property (nonatomic,weak)id<ViewControllerDelegate> delegate;
如果我们想要向外传出一些内容,我们可以建立对应的方法或者点击方法
- (void)pushToNextView
{
if ([self.delegaterespondsToSelector:@selector(transform:)]) {
[self.delegatetransform:@"我是代理传值"];
}
}
然后我们在对应的页面去遵守代理,然后写入代理方法就可以获取传来的数值
第三:block传值,传值方式类似属性传值,但是要比属性传值灵活很多,但是没有代理传值的范围广泛,接下来来看一下简单的代码示例
代码示例:首先我们需要在需要传出数值的地方定义代码块
@property (nonatomic,strong)void (^newBlock)(NSString *,NSInteger);
定义好代码块之后我们需要在对应的按钮方法,或者调用的类方法
- (void)pushToNextView
{
self.newBlock(@"我是代码块传值!",123);
[self.navigationControllerpopViewControllerAnimated:YES];
}
这里可以将我们需要的数值传出去,当然我们接收代码块的地方也必须是在调用的地方使用代码块
- (void)pushToSecondView
{
SecondViewController * secondVC = [[SecondViewControlleralloc]init];
//Block定义
//^(参数类型昵称){执行代码 }
secondVC.newBlock = ^(NSString *str,NSInteger age){
self.name = str;
self.age = age;
};
[selfpresentViewController:secondVC animated:YEScompletion:nil];
}
这样我们就可以获取到代码块中的数据了
四:通知传值:通知传值有两个对应的方法一个是[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(receiveData:)name:@"receive"object:nil];可以添加监听对象
另一个是[[NSNotificationCenterdefaultCenter] postNotificationName:@"receive"object:jumpBtn];可以发送被监听对象的属性内容
当我们接收到监听内容对象变动的时候就会调用我们在添加监听类中定义好的方法
- (void)receiveData:(NSNotification *)noti
{
self.btn = noti.object;
}
就可以获取到被监听对象的属性了
以上就是目前常用的四个传值类型的简单实用,希望大家看到有错误的地方请多指正,谢谢!