0

我对 iOS 开发非常陌生,我正在努力制作一个连接到 BLE 设备的应用程序。由于我有许多视图控制器,我需要让外围设备始终连接到所有视图控制器中。

为了实现这一点,我在一个Singleton. 这很好用,我从外围调用连接方法View ControllerSingleton连接到外围设备。

现在,问题是我的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 ControllerSingleton. 也不知道我尝试的方式是否正确。

任何建议或帮助将不胜感激。谢谢。

-----更新: -----

多亏了 Mundi 和 Nikita,我有了更好的方法来通过 NSNotification 实现我需要的东西。对于所有需要它的人,我就是这样做的:

在我View ControllerviewDidLoad电话中:

[[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”)。

4

2 回答 2

3

你需要使用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
}

西格尔顿)

- (void) foo {
    /// some actions

    // device connected
    [[NSNotificationCenter defaultCenter] postNotificationName:DeviceStateChanged object:self];

    ///
}

建议:将通知名称移动到您的常量并使用常量名称。有关命名约定,请查看 Apple 指南

于 2014-07-21T09:13:19.350 回答
1

正确的方法是通过NSNotification. 该通信设备正是针对这种情况而设计的。它广播消息而不关心潜在的接收者是否可用。

在您的视图控制器中,当它们出现/消失时,您调用NSNotificationCenter's addObserver/ 。removeObserver您通过 发布通知postNotification:

于 2014-07-21T09:06:23.467 回答