(8) iphone 开发 数据传递 01. NSNotification 通知机制演示

一:利用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

图解:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值