我有一些 bluetooth
类需要在所有 View 期间都处于事件状态。
这意味着,我必须从不同的 View 调用此类中的函数,并且还要从此类获取委托(delegate)到不同的 View 。
所以,我必须初始化它一次才能创建连接,然后,我必须从不同的 View (类)再次使用它并注册以从中获取通知。
我正在考虑一个单例
,他将创建该蓝牙类的一个实例,我可以从任何地方访问他。
但是,我还希望任何 View 都可以从中获取委托(delegate)
。
我该怎么做? 我已阅读What should my Objective-C singleton look like?
但是也许singleton
不是我需要的?
如何创建一个始终处于事件状态的类,并注册以从任何地方获取代表?
(如何使用 app delegate
类来完成?)
最佳答案
不久前我也有过类似的查询
问题:多个类需要从单个实例接收委托(delegate)调用
解决方案:我结合使用了sharedInstance、委托(delegate)和NSNotifications来处理问题
共享实例
+ (SomeBluetoothClass *) sharedInstance {
static dispatch_once_t once;
static SomeBluetoothClass *sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
委托(delegate)
@property (weak, nonatomic) id <SomeBluetoothClassDelegate> delegate;
因为委托(delegate)一次只能响应一类。根据您的逻辑分配重点类(class)。然后,每当您想要向所有人发送信息时,都可以使用共享实例中的 NSNotificationCenter 发送信息。通过使用 NSNotifications 的 userInfo 字典发送信息
通知
[[NSNotificationCenter defaultCenter] postNotificationName:SomeBluetoothClassNotification
object:self
userInfo:info];
将 SomeBluetoothClass 的结构建模为线程安全,并与委托(delegate)一起处理所有通知,它应该可以正常工作。
关于ios - 有代表的单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28579059/