iOS开发中常用到的传值方法

2018-08-23  本文已影响0人  瓊胖子

iOS开发中我们经常用到的传值方法无非4种:

1.我们需要将上个页面的值通过跳转传到下一个页面中,也就是正向传值,这是最简单的。

我们第一个页面为OneViewController,跳转的第二个页面为TwoViewController,只需在跳转的时候将TwoViewController创建实例化,并给需要接收的属性赋值即可。

 TwoViewController * TwoVC=[[TwoViewController alloc]init];

    TwoVC.itmestr=@"456";

    [self.navigationController pushViewController:TwoVC animated:YES];

当然还需要在TwoViewController.h文件中声明可供外部访问接收值的属性

@property(nonatomic ,copy)NSString * itmestr;

2.在我们开发中还需要用到的常用的反向传值的方法还有代理delegate(方法一)

我们需要将A类中的值传到B类中(就是当前处于B类中,操作B类中创建的A类并将A类的数据返向传值给了B类)

@protocol A类Delegate<NSObject>

- (void)A类Delegate方法名:(NSMutableArray*)SenderArray;//传递值获取的方法也是B类需要实现的方法

@end

@property(nonatomic,assign)id<A类Delegate>delegate;//声明delegate属性

在需要反向传值的地方判断B类是否遵循了代理并进行传值

  if([self.delegaterespondsToSelector:@selector(A类Delegate方法名:)]) {

        [self.delegate A类Delegate方法名:self.selectArray];

    }

B类:

首先B类遵循A类的Delegate,既:

@interface B类ViewController ()<A类Delegate>

@optional

@end

然后实例话A类

A类 * A=[A类 alloc]init];

A.delegate=self;

实现代理方法:

- (void)A类Delegate方法名:(NSMutableArray*)SenderArray{

此时的SenderArray就是从A类中传过来的数据;

}

2.在我们开发中还需要用到的常用的反向传值的方法还有Block(方法二)

首先我们需要在需要往外传值的类中先声明一个block:

typedef void(^block名称Block) (参数类型“就是传入的属性类型” *参数名“传入的值的名称”);

然后再声明一个block的属性:

@property(nonatomic,copy)block名称Block  属性名称Block;

然后再需要传值的时候写入值:

  __weak typeof(self) weakself = self;

                        if(weakself.属性名称Block) {

                            //将自己的值传出去,完成传值

                            weakself.属性名称Block(需要穿的值);

       }

最后我们只需将要接收值的时候把被传值的类声明的属性调用该block的属性即可

   被传值的类VC.属性名称Block= ^(NSString * 参数名“传入的值的名称”){

           _UserNickname=参数名“传入的值的名称”;

        };

3.我们在开发中再不受任何限制的情况下还有一种传值方法就是通知NSNotificationCenter(方法三)

首先在接收传递值类中注册一个通知

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(通知的方法:) name:@"通知名" object:nil];

实现通知的方法并接收传递的值

-(void)通知的方法:(NSNotification*)sender{

}

在通知不需要的时候记住要移除通知

- (void)removeObserver:(id)observer;

- (void)removeObserver:(id)observer name:(nullableNSNotificationName)aName object:(nullableid)anObject;

在需要去更改的类中发送通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"通知的名称" object:传递的参数];

欢迎指正!!!

上一篇下一篇

猜你喜欢

热点阅读