关于iOS中使用通知进行传值

2017 年 12 月 30 日 0 条评论 1.66k 次阅读 0 人点赞

界面之间的传值有很多方法,最基本的是可以实例化对象进行传值,也可以使用block块或者是使用通知进行传值。它们也各有优缺点,第一种最简单,但是在使用ARC环境的情况下这种方式还是不推荐的,因为你可能会因为一个值搞死也传不过去,究竟什么原因那。这是因为在ARC环境下,你传的值被提前释放了,这个问题想必做过开发的程序猿都是会遇到的。费劲脑汁了吧,这里说一下iOS中使用通知进行传值的方法:

首先使用通知你需要在接收方添加一个通知即注册通知监听器,通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;  
   //observer:监听器,即谁要接收这个通知  
   //aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入  
   //aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知  
   //anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知  
     
     
   - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block;  
   //name:通知的名称  
   //obj:通知发布者  
   //block:收到对应的通知时,会回调这个  
   //blockqueue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行  
   通知  
   一个完整的通知一般包含3个属性:  
   - (NSString *)name; // 通知的名称  
   - (id)object; // 通知发布者(是谁要发布通知)  
   - (NSDictionary *)userInfo; // 一些额外的信息(通知发布者传递给通知接收者的信息内容)  

初始化一个通知(NSNotification)对象:

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo   
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;  
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;  

发布通知:发布一个通知可以在notification对象中设置通知的名称、通知的发布者和额外信息等;

- (void)postNotification:(NSNotification *)notification;  
- (void)postNotificationName:(NSString *)aName object:(id)anObject;  
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;  

移除通知:

- (void)removeObserver:(id)observer;  
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;  

示例:在两个类之间传值
在接受类中注册通知监听器

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangeImage:) name:@"changeImage" object:nil];  

实现监听回来的方法:

- (void)onChangeImage:(NSNotification*)sender  
{  
    self.resultOKNumbers = sender.object;  
    self.dic = sender.userInfo;  
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"确定提交本次绘画吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
    alertView.tag = 100002;  
    alertView.delegate = self;  
    [alertView show];  
}  

上级界面发送通知:


[[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:text]; 
//或者是传多个参数:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:text userInfo:dic];  

当通知发出后就会执行监听的方法,在方法中通过sender.object获得传过来的对象,当需要传多个值的时候可以只用数组或者是字典作为传过来的对象。

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)