我对 iOS 开发非常陌生,我正在努力制作一个连接到 BLE 设备的应用程序。由于我有许多视图控制器,我需要让外围设备始终连接到所有视图控制器中。
为了实现这一点,我在一个Singleton
. 这很好用,我从外围调用连接方法View Controller
并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"];
然后我尝试在 main 中创建一个方法View Controller
:
- (void) updateLabel:(NSString *) labelText{
NSLog(@"CALLED IN MAIN");
self.myLabel.text = labelText;
}
并从以下位置调用它Singleton
:
MainViewController *controller = [[MainViewController alloc] init];
[controller updateLabel:@"TEST"]
哪个被正确调用(NSLog
已显示)但标签未更新。
我真的不知道如何View Controller
从Singleton
. 也不知道我尝试的方式是否正确。
任何建议或帮助将不胜感激。谢谢。
-----更新: -----
多亏了 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”)。