gpt4 book ai didi

ios - CBCentralManagerDelegate 没有在 NSObject 中被调用

转载 作者:行者123 更新时间:2023-12-01 18:54:02 26 4
gpt4 key购买 nike

我创建一个继承自 NSObject 的类并添加delegate方法。在我的类里面,我想使用 CBCentralManager 及其委托(delegate)方法。但是委托(delegate)方法没有被调用。这是我的代码 -

这是 VZBluetooth.h

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>

@protocol BluetoothDelegate <NSObject>

@required
-(void)getBluetoothStatus:(NSString*)status;

@end

@interface VZBluetooth : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong) id<BluetoothDelegate> delegate;
-(void)callBluetooth;

@end

对于 VZBluetooth.m
@implementation VZBluetooth
{
NSString *status;
CBCentralManager *ce;

}
@synthesize delegate = _delegate;

-(void)callBluetooth
{
ce = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark - Bluetooth Delegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{

if(central.state == CBCentralManagerStatePoweredOn){
if ([central respondsToSelector:@selector(scanForPeripheralsWithServices:options:)]) {
status = CASE_STATUS_PASS;
}
else{
status = CASE_STATUS_FAIL;
}

}
else{
status = CASE_STATUS_FAIL;
}

if ([self.delegate respondsToSelector:@selector(getBluetoothStatus:)]) {
[self.delegate getBluetoothStatus:status];
}
}

我的电话——
VZBluetooth *blu = [[VZBluetooth alloc]init];
[blu callBluetooth];
blu.delegate = self;

最佳答案

您正在分配您的 VZBluetooth实例作为局部变量 - 所以一旦该函数退出,它将被释放。这几乎可以肯定是在蓝牙功能被初始化并有机会调用委托(delegate)方法之前。

您需要将实例存储在 strong 上您调用类中的属性。

其他一些建议,您的delegate位于 VZBluetooth 的属性(property)应该是 weak而不是 strong为了防止保留循环,您可以简化 centralManagerDidUpdateState方法相当 -

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{

status=CASE_STATUS_FAIL;

if(central.state == CBCentralManagerStatePoweredOn){
if ([central respondsToSelector:@selector(scanForPeripheralsWithServices:options:)]) {
status = CASE_STATUS_PASS;
}
}
if ([self.delegate respondsToSelector:@selector(getBluetoothStatus:)]) {
[self.delegate getBluetoothStatus:status];
}
}

关于ios - CBCentralManagerDelegate 没有在 NSObject 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972961/

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