【发布时间】:2014-09-11 17:35:15
【问题描述】:
我对 iOS 开发非常陌生,我正在努力制作一个连接到 BLE 设备的应用程序。由于我有许多视图控制器,因此我需要始终保持外围设备在所有视图控制器中的连接。
为了实现这一点,我在 Singleton 中实现了所有 BLE 连接方法。这很好用,我从View Controller 调用connect 方法,Singleton 连接到外围设备。
现在,问题是我的视图控制器中有一个 UILabel,我想使用来自 Singleton 的连接状态(扫描、连接、连接、断开连接)进行更新。
所以我尝试从View Controller 获取实例并直接更改标签,例如:
MainViewController *controller = [[MainViewController alloc] init];
controller.myLabel.text = @"TEST";
我还实例化了视图控制器类,例如:
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle: nil];
MainViewController *controller = (MainViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@"MainVC"];
然后我尝试在主View Controller创建一个方法:
- (void) updateLabel:(NSString *) labelText{
NSLog(@"CALLED IN MAIN");
self.myLabel.text = labelText;
}
并从Singleton 中调用它,例如:
MainViewController *controller = [[MainViewController alloc] init];
[controller updateLabel:@"TEST"]
调用正确(显示NSLog)但标签未更新。
我真的不知道如何从Singleton 更新我的View Controller 标签。也不知道我尝试的方式是否正确。
任何建议或帮助将不胜感激。谢谢。
----- 更新: -----
感谢 Mundi 和 Nikita,我获得了更好的方法来通过 NSNotification 实现我需要的东西。对于所有需要它的人,我就是这样做的:
在我的View Controller 在viewDidLoad 我打电话:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionLabel:) name:@"connectionLabelNotification" object:nil];
然后在同一个类中我实现通知观察器方法,如:
- (void)updateConnectionLabel:(NSNotification *) notification {
if ([[notification name] isEqualToString:@"connectionLabelNotification"]) {
self.connectionLabel.text = notification.object; //The object is a NSString
}
}
然后在我的Singleton,当我需要时,我会打电话:
[[NSNotificationCenter defaultCenter] postNotificationName:@"connectionLabelNotification" object:[NSString stringWithFormat:@"CONNECTED"]];
当View Controller 收到来自Singleton 的通知时,它会使用我在通知对象上添加的文本更新标签(在本例中为@"CONNECTED")。
【问题讨论】:
标签: ios objective-c singleton bluetooth-lowenergy cbcentralmanager