iOS 本地通知

来源:互联网 发布:数控铣削加工编程例题 编辑:程序博客网 时间:2024/05/17 08:06

学习iOS 也有一段时间了,通知还没有看过,今天学习了一下;

通知主要是用于不同对象之间的数据共享和线程通信(这些专业的词组我也不太懂,弄明白什么事,什么时候该用就行了)。

看了无线互联的关于本地通知的视频(只有一个简单地例子),不过正适合我的胃口。

例子应用场景:

一个child类,在类中有个NSInteger属性初始化为100,定义一个定时器每两秒钟让这个属性值减2,当减到90的时候,想通知中心发送一个通知。

一个father类,在类中注册接收这个通知,当child发送通知的时候father来接收这个通知并作出相应地反映。

@interface Child : NSObject@property (nonatomic,assign) NSInteger  num;@end

#import "Child.h"@implementation Child@synthesize num;- (id)init{    self = [super init];    if (self) {        num = 100;        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeobserver:) userInfo:nil repeats:YES];    }    return self;}- (void)timeobserver:(NSTimer *)timer{    NSLog(@"child:%ld",num);    num -= 2;    if (num == 90) {        [[NSNotificationCenter defaultCenter]postNotificationName:@"child" object:[NSNumber numberWithInteger:num]];//第一个参数为该通知的名字,用于识别通知,第二个参数object为传递的参数            }}@end

@implementation Father-(id)init{    self = [super init];    if (self) {        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(observer:) name:@"child" object:nil];//注册接收通知,<pre name="code" class="objc">如果第四个参数为nil<span style="font-family: Arial, Helvetica, sans-serif;">表示接收名字为name(第三个参数)的通知,如果第四个参数指定对象,那么只接收该对象下名为name的参数。</span>
} return self;}- (void)observer:(NSNotification *)notification{ NSInteger i = (NSInteger) notification.object; NSLog(@"%ld",(long)i);}@end



2 0