iOS 开发 Notification传值


通知传值


第一个UIViewcontroller.h

#import <UIKit/UIKit.h>

@interface UseNotifi_VCOne :UIViewController

@end

UIViewcontroller.m

- (void)viewDidLoad
{
   [super viewDidLoad];
   // Do any additional setup after loading the view from its nib.
   
   
   //监听某个通知
   //这里需要注意到 : 通知只能是 对象才可用,且该对象必须存在于内存中
   /*
    [NSNotificationCenter defaultCenter] 获取通知的管理
    addObserver: 设置通知的监听者
    */
   //NOTIFICATION_CHANHECONTENT 在 QFUseNotifi_VCTwo中
   [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(contentChange:) name:NOTIFICATION_CHANGECONTENT object:nil];
   
}

-(void)dealloc
{    //       通知
   //         |
  //         \ /
 //    对象-->监听<--通知
//  将当前对象监听的所有通知移除
   [[NSNotificationCenter defaultCenter]  removeObserver:self];
   
   //移除指定name关联的通知
   [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_CHANGECONTENT object:nil];
}
//收到通知后,触发的方法,然后做相应的处理
-(void)contentChange:(NSNotification *)notification
{                                                                  
                                                         //userInfo : 通知里捆绑的数据
   self.detailLab.text = [NSString stringWithFormat:@"“%@” 发来贺电",[notification.userInfo objectForKey:@"ChangeContent"]];
}

#pragma mark - 用户交互(push第二个控制器UseNotifi_VCTwo)

- (IBAction)gotoPostNotifiVC:(id)sender {
   
   UseNotifi_VCTwo *vc = [[UseNotifi_VCTwo alloc] init];
   
   [self.navigationController pushViewController:vc animated:YES];
   
}


第二个UIviewController( UseNotifi_VCTwo.h)

#import <UIKit/UIKit.h>

/*
通知的发送者     xxxxxxxxxxxxxxxxxxxxxxxxxx
*/

//定义 通知的 标识,根据需要选择将 #define 定义在具体的文件中,如.pch、.h等
#define  NOTIFICATION_CHANGECONTENT @"Notification_ChangeContent"//通知的标识

@interface UseNotifi_VCTwo : UIViewController

@end

第二个UIviewController( UseNotifi_VCTwo.m)

@interface UseNotifi_VCTwo ()

@property (weak, nonatomic) IBOutlet UITextField *nameTF;

@end

@implementation UseNotifi_VCTwo

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
       // Custom initialization
       self.title = @"发送通知的控制器";
   }
   return self;
}

- (void)viewDidLoad
{
   [super viewDidLoad];

}

- (void)didReceiveMemoryWarning
{
   [super didReceiveMemoryWarning];
}

#pragma mark - 用户交互(post回去)
- (IBAction)postNotificationAction:(id)sender {
   
   NSString *uname = self.nameTF.text;
   NSDictionary *ChangeContent = [NSDictionary dictionaryWithObject:uname forKey:@"ChangeContent"];
   
   //发送一个通知
   /*
    [NSNotificationCenter defaultCenter]  获取全局通知对象
    postNotificationName: 通知的标识,必须设置
    object: 用于通知的过滤,将通知捆绑一个obj,一般设为nil
    userInfo: 发送通知所捆绑的用户数据
    */
    [[NSNotificationCenter defaultCenter]
    postNotificationName:NOTIFICATION_CHANGECONTENT
                  object:nil
                userInfo:ChangeContent];
   
   [self.navigationController popViewControllerAnimated:YES];
}

@end