gpt4 book ai didi

ios - 未在不同线程上调用委托(delegate)

转载 作者:可可西里 更新时间:2023-11-01 04:15:38 25 4
gpt4 key购买 nike

我正在尝试使用 CoreBluetooth 框架,并且我创建了一个辅助类 (btHelper) 来使代码更易于维护等。

问题在于,在这个帮助类中,当所有内容都被混入大类时,委托(delegate)方法不再像最初那样被调用。是的,我已经在助手类的 .h 中设置了委托(delegate)方法,是的,我已经将对象 CBCentralManager 委托(delegate)设置为 self。我几乎完成了所有事情,就像在一节课上做的一样。我相信它与主线程有关,但我在这方面的经验很少。

具体来说,我要调用的委托(delegate)方法是

-(void)centralManagerDidUpdateState:(CBCentralManager *)central 

任何人都可以告诉我我必须做什么才能让委托(delegate)调用在这个帮助程序类中正常工作吗?谢谢!

下面是PrimaryViewController类和btHelper类

btHelper.m

-(void) activateBluetooth
{
self.manager= [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//DELEGATE METHOD THAT NEVER GETS CALLED. SHOULD BE CALLED AS SOON AS self.manager is initiated
self.isAvailable=FALSE;
switch (central.state) {
case CBCentralManagerStatePoweredOff:
NSLog(@"CoreBluetooth BLE hardware is powered off");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
self.isAvailable=TRUE;
break;
case CBCentralManagerStateResetting:
NSLog(@"CoreBluetooth BLE hardware is resetting");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"CoreBluetooth BLE state is unauthorized");
break;
case CBCentralManagerStateUnknown:
NSLog(@"CoreBluetooth BLE state is unknown");
break;
case CBCentralManagerStateUnsupported:
NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
break;
default:
break;
}

}

PrimaryViewController.m

-(IBAction)connect
{
btHelper *bluetoothManager= [[btHelper alloc]init];
[bluetoothManager activateBluetooth];

}

最佳答案

您的助手实例是 -connect 方法中的局部变量。所以 ARC 在您可以接收委托(delegate)方法之前释放它(和 CBCentralManager 实例)。让您的助手成为 PrimaryViewController 的实例变量(或属性),这将解决您的问题。

@interface PrimaryViewController : UIViewController
{
// BTHelper instead of btHelper, to follow naming convention
BTHelper *_bluetoothManager;
}
@end

@implementation PrimaryViewController
-(IBAction)connect
{
// FIXME: this don't check if _bluetoothManager is already instantiated
_bluetoothManager = [[BTHelper alloc] init];
[_bluetoothManager activateBluetooth];
}
@end

关于ios - 未在不同线程上调用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com