### 一:利用NSNotification與UIAlertVeiw演示:通知(通常指發送消息的一方),與,觀察者(值接收消息的一方)間的通信。通知與觀察者是兩個相互獨立的類。
### ?程序效果:

### (1)首先創建一個繼承自UIViewController的類:MyObserver.h ? 。(作為觀察者)
1)MyObserver.h ??
~~~
#import <UIKit/UIKit.h>
#import "MyClass.h"
@interface MyObserver : UIViewController
@property(retain) MyClass *myclass;
-(void)updata:(NSNotification*)notifi;
@end
~~~
1)MyObserver.m
~~~
#import "MyObserver.h"
@implementation MyObserver
@synthesize myclass;
- (void)viewDidLoad
{
//注意這里的myclass必須為全局變量,不可 MyClass *myclass=[[MyClass alloc] init];這樣寫。
self.myclass=[[MyClass alloc] init];
//定義彈出對話框,注意這里的delegate:myclass 必須為myclass,這樣MyClass才能執行點擊按鈕后的操作。
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"hello" message:@"DongStone" delegate:myclass cancelButtonTitle:@"cancle" otherButtonTitles:@"back", nil];
//向通知中添加類,使其成為觀察者,來接收消息。self代表當前類,selector:接到通知后要執行的方法,name:在符合(object:范圍內的通知)在發送消息時配對查找的標示pass。這里object:nil 為可以接受任何類型發送的通知。name與object兩個條件必須同時滿足。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updata:) name:@"pass" object:nil];
//使對話框顯示
[alert show];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
//這個方法是自定義的,用于接收數據
-(void)updata:(NSNotification *)notifi{
NSString *str=[[notifi userInfo] objectForKey:@"key"];
UIAlertView *al=[[UIAlertView alloc] initWithTitle:@"消息已經傳了過來" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[al show];
}
~~~
### (2)創建一個普通的類(MyClass.h) (繼承什么都可以,因為此程序中他不需有太多功能)。(作為通知)
2)MyClass.h
~~~
#import <Foundation/Foundation.h>
@interface MyClass : NSObject<UIAlertViewDelegate>
@end
~~~
2) MyClass.m
~~~
#import "MyClass.h"
@implementation MyClass
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
//實現方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//由于方法userInfo所能接收的類型為NSDictionary。
NSString *str=[[NSString alloc] initWithFormat:@"點擊按鈕的下標是:%d",buttonIndex];
NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:str,@"key", nil];
//發送消息.@"pass"匹配通知名,object:nil 通知類的范圍
[[NSNotificationCenter defaultCenter] postNotificationName:@"pass" object:nil userInfo:dic];
}
@end
~~~
### 圖解:

- 前言
- (1) iphone開發,自定義Window-based Application 模板及委托運行機制
- (2) iphone 開發 表視圖UITableView結構深層剖析
- (3) iphone 開發 從應用程序看UITableView的:分組,分區,索引,工作原理及其變換法則,plist文件數據定義規則
- (4) iphone 開發 自定義UITableViewCell的子類 ,輕松添加圖片文本信息等
- (5) iphone 開發 在表視圖(UITableView) 中利用UISearchBar實現數據的搜索,視圖的多功能化
- (6) iphone 開發 真正理解委托(delegate)與數據源(data source)
- (7)---01 iphone 開發 數據傳遞 NSNotification 通知機制演示
- (7)---02 iphone 開發 數據傳遞 : 頁面切換與數據的反向傳遞以及協議(protocol)作用的體現
- (8)---01 iphone 開發 大話分析導航欄NavigationController
- (9) iphone 開發 AppSettings , 系統setting與應用程序setting間的數據控制
- (10) iphone 開發 用戶點擊,觸摸和手勢識別 解析