一:利用NSNotification与UIAlertVeiw演示:通知(通常指发送消息的一方),与,观察者(值接收消息的一方)间的通信。通知与观察者是两个相互独立的类。

 程序效果:

iphone 开发 数据传递 01. NSNotification 通知机制演示_发送消息
 

(1)首先创建一个继承自UIViewController的类:MyObserver.h   。(作为观察者)

1)MyObserver.h   
[plain] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2. #import "MyClass.h"  
  3. @interface MyObserver : UIViewController  
  4. @property(retain) MyClass *myclass;  
  5. -(void)updata:(NSNotification*)notifi;  
  6. @end  
1)MyObserver.m
[plain] view plaincopy
  1. #import "MyObserver.h"  
  2.   
  3. @implementation MyObserver  
  4.   
  5. @synthesize myclass;  
  6.   
  7. - (void)viewDidLoad  
  8. {  
  9.     //注意这里的myclass必须为全局变量,不可 MyClass *myclass=[[MyClass alloc] init];这样写。  
  10.     self.myclass=[[MyClass alloc] init];  
  11.       
  12.     //定义弹出对话框,注意这里的delegate:myclass 必须为myclass,这样MyClass才能执行点击按钮后的操作。  
  13.     UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"hello" message:@"DongStone" delegate:myclass cancelButtonTitle:@"cancle" otherButtonTitles:@"back", nil];  
  14.       
  15.     //向通知中添加类,使其成为观察者,来接收消息。self代表当前类,selector:接到通知后要执行的方法,name:在符合(object:范围内的通知)在发送消息时配对查找的标示pass。这里object:nil 为可以接受任何类型发送的通知。name与object两个条件必须同时满足。  
  16.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updata:) name:@"pass" object:nil];  
  17.     //使对话框显示  
  18.     [alert show];  
  19.     [super viewDidLoad];  
  20.     // Do any additional setup after loading the view from its nib.  
  21. }  
  22. //这个方法是自定义的,用于接收数据  
  23. -(void)updata:(NSNotification *)notifi{  
  24.     NSString *str=[[notifi userInfo] objectForKey:@"key"];  
  25.     UIAlertView *al=[[UIAlertView alloc] initWithTitle:@"消息已经传了过来" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:nil];  
  26.     [al show];  
  27. }  


(2)创建一个普通的类(MyClass.h) (继承什么都可以,因为此程序中他不需有太多功能)。(作为通知)

2)MyClass.h

 

[plain] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface MyClass : NSObject<UIAlertViewDelegate>  
  4.   
  5. @end  


2) MyClass.m

 

 

 

 

 

[plain] view plaincopy
  1. #import "MyClass.h"  
  2.   
  3. @implementation MyClass  
  4.   
  5. - (id)init  
  6. {  
  7.     self = [super init];  
  8.     if (self) {  
  9.     }  
  10.     return self;  
  11. }  
  12. //实现方法  
  13. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{  
  14.       
  15.     //由于方法userInfo所能接收的类型为NSDictionary。   
  16.     NSString *str=[[NSString alloc] initWithFormat:@"点击按钮的下标是:%d",buttonIndex];  
  17.     NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:str,@"key", nil];  
  18.       
  19.     //发送消息.@"pass"匹配通知名,object:nil 通知类的范围  
  20.     [[NSNotificationCenter defaultCenter] postNotificationName:@"pass" object:nil userInfo:dic];  
  21. }  
  22.   
  23. @end  

图解:

iphone 开发 数据传递 01. NSNotification 通知机制演示_发送消息_02