我是 iOS 开发的新手,我正在努力制作一个连接到 BLE 设备的应用程序。因为我有很多 View Controller ,所以我需要在所有 View Controller 中始终保持外围设备连接。
为此,我在 Singleton
中实现了所有 BLE 连接方法。 .这很好用,我从 View Controller
调用连接方法和 Singleton
连接到外围设备。
现在,问题是我有一个 UILabel
在我的 View Controller 中,我想使用来自 Singleton
的连接状态(扫描、连接、连接、断开连接)进行更新.
所以我尝试从 View Controller
中获取实例并像这样直接更改标签:
MainViewController *controller = [[MainViewController alloc] init];
controller.myLabel.text = @"TEST";
我还实例化了 View Controller 类:
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")。
最佳答案
你需要使用NSNotification
。
示例代码如下:
在viewDidLoad中:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mySelector:)
name:DeviceStateChanged
object:nil];
在dealloc中:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:DeviceStateChanged
object:nil];
还在ViewController中添加一个方法:
- (void) mySelector:(NSNotification *) notification {
// action performed
}
在 Sigleton 中
- (void) foo {
/// some actions
// device connected
[[NSNotificationCenter defaultCenter] postNotificationName:DeviceStateChanged object:self];
///
}
建议:将通知名称移至常量并使用常量名称。有关命名约定,请参阅 Apple 指南
关于ios - 从单例更改 View Controller 中的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861276/