私は iOS 開発が初めてで、BLE デバイスに接続するアプリの作成に苦労しています。多くのView Controllerがあるため、すべてのView Controllerで周辺機器を常に接続しておく必要があります。
これを実現するために、すべての BLE 接続メソッドをSingleton
. これはうまく機能します。私は connect メソッドを呼び出して、周辺機器View Controller
に接続します。Singleton
さて、問題は、UILabel
からの接続状態(スキャン中、接続中、接続中、切断中)で更新したいView Controllerにあること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
が表示されました) が、ラベルは更新されませんでした。
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") でラベルを更新します。