IOS 广播机制与 android 广播机制对比

来源:互联网 发布:德州软件开发 编辑:程序博客网 时间:2024/04/30 14:48

Android下广播机制的实现机制:

1.发送 Context的 sendBroadcast实现,传入Intent即可,Intent提供了携带很多基本类型等的方法,如果想传递复杂对象,应该实现Parcelable接口,Parcelable接口提供了对象序列化的一系列方法。

2.接收 接收主要有两种方法:

一、在AnroidManifest.xml种注册,需要单独实现一个receiver (继承自BroadcastReceiver ,实现onReceive方 法),这种方法注册的永远有效

二、代码注册的方法实现,自定义好IntentFilter,调用Context的registerReceiver的方法,用这种方法实现,需要在当前上下文生命周期方法调用unRegisterReceiver,否则导致内存泄漏。

iOS下实现类似广播机制是要利用NSNotificationCenter。

1. 注册(也可以理解为接收)

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive:) name:@"_post" object:obj];

注意在实现onReceive方法时应该传递NSNotification对象,和Intent有一样

-(void)onReceive:(NSNotification *) notification{
//do your task

// 通过NSNotification 的各种方法可以取出各种参数


- (NSString *)name;
- (id)object;
- (NSDictionary *)userInfo;

//
}

2.发送 ,其中name是NSNotification的唯一标示,object可以传递各种参数,userInfo 字典类信息

[[NSNotificationCenter defaultCenterpostNotificationName:@"_post"object:objuserInfo:userInfo];

0 0
原创粉丝点击