码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 本地通知

时间:2014-10-27 17:43:02      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:ios

学习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




iOS 本地通知

标签:ios

原文地址:http://blog.csdn.net/u010123208/article/details/40509255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!