我有一个像我这样使用的对象
[PeripheralManager readValueForCharacteristic:[CBUUID UUIDWithString:CHARACTERISTIC_TX_POWER_LEVEL]
inService:[CBUUID UUIDWithString:SERVICE_TX_POWER]
completionBlock:^(NSData *value) {
//code
}];
问题是如果我在调用completionBlock
时没有将对象保存在强大的属性中,则应用程序崩溃。
你可以说"将你的PeripheralManager保存在一个强大的属性中......好吧,在某些情况下,我必须读取一个值而不是另一个值,等等,也许是3或4次。
在其他情况下,可能会调用类方法,该方法返回块中的某些值,并且不会释放块。有没有办法将mi PeripheralManager保留在内存中?
修改
+ (id)readValueForCharacteristic:(CBUUID *)cUUID
inService:(CBUUID *)sUUID
completionBlock:(completionBlock)completionBlock
{
return [[self alloc] initForReadValueForCharacteristic:cUUID
inService:sUUID
completionBlock:completionBlock];
}
- (id)initForWriteValue:(unsigned char)value
forCharacteristic:(CBUUID *)cUUID
inService:(CBUUID *)sUUID
completionBlock:(completionBlock)completionBlock
{
self = [super init];
if (self)
{
self.completionBlock = [completionBlock copy];
self.accessType = PeripheralAccessTypeWrite;
self.valueToSet = value;
if (cUUID && sUUID)
{
self.sUUID = sUUID;
self.cUUID = cUUID;
self.connectedPeripheral = [[BLEManager manager] getConnectedPeripheral];
self.connectedPeripheral.delegate = self;
if (self.connectedPeripheral && self.connectedPeripheral.state == CBPeripheralStateConnected)
{
[self.connectedPeripheral discoverServices:@[sUUID]];
}
}
else NSLog(@"cUUID and sUUID are mandatory");
}
return self;
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
// NSLog(@"didDiscoverServices");
for (CBService *service in peripheral.services)
{
if ([service.UUID isEqual:self.sUUID])
{
[peripheral discoverCharacteristics:@[self.cUUID] forService:service];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (service.UUID.UUIDString.length >= 8)
{
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:self.cUUID])
{
if (self.accessType == PeripheralAccessTypeRead)
{
self.connectedCharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
[peripheral readValueForCharacteristic:characteristic];
}
else
{
self.connectedCharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
unsigned char dat = self.valueToSet;
NSLog(@"dat %i", dat);
NSData * valueData = [NSData dataWithBytes:&dat length:1];
NSLog(@"valueData %@",valueData);
[peripheral writeValue:valueData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error)
{
NSLog(@"%@",error.localizedDescription);
}
else
{
NSString * characteristicName = [self getCharacteristicName:characteristic];
NSData * value = [self readValueFromCharacteristic:characteristic];
NSLog(@"update %@: %@",characteristicName ,value);
self.completionBlock(value);
}
}
由于