如何使用应用程序委托中的视图控制器的function?

我有一个通过蓝牙连接到设备的应用程序。

我希望应用程序发送一个命令,指示应用程序将在应用程序委托方法中closures:(void)applicationWillTerminate:(UIApplication *)application {

一个字: NSNotificationCenter

我不确定您需要设置数据,因为您无法通过NSNotificationCenter无缝传递数据; 不过你要在你的UIApplicationDelegate中弄明白,那么为什么你不能直接在视图控制器中执行它。

在你的情况下,你不需要在你的应用程序委托中做任何事情 ,因为这个通知允许你的视图控制器作为一个迷你应用程序委托 (你可以得到终止状态等等)。

因此…

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TXdata:) name:UIApplicationWillTerminateNotification object:nil]; } - (void)TXdata:(NSString *) data { NSString *newData = data; if (newData == nil) { newData = ... // Figure out what your data should be here. } //do whatever with your data here. } 

我引用:

UIApplicationWillTerminateNotification

当应用即将终止时发布。

此通知与委托applicationWillTerminate:方法关联。 此通知不包含userInfo字典。

您应该创build一个独立于视图控制器和应用程序委托的类来处理BLE通信。 这样,视图控制器和应用程序委托都可以访问,并为您的应用程序提供更好的“关注点分离”。 这个新class级可能作为一个单身人士很好。