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




原文地址:https://www.cnblogs.com/zfyouxi/p/4318764.html