ios 如何让一个方法在运行前先判断是否符合条件,符合就运行,否则等待符合条件再去运行
在做蓝牙的项目,一个单片机需要调用OC的收发方法,发送没问题了,但是读取蓝牙返回数据的时候,那个数据还没有接收到,我要如何做才能让他等待接收到数据后再去运行?
这是读取蓝牙广播的数据的方法
- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error)
{
NSLog(@"Error receiving notification for characteristic %@: %@", characteristic, error);
return;
}
else
{
[self.lock lock];
NSLog(@"\n准备查看收到的数据");
//接受的数据
NSData*receiveData= [NSData dataWithData:characteristic.value];
//把收到的数据保存到数组
[self.array addObject:receiveData];
//对存储在数组里的
[self.lock unlock];
}
}
/**
* 读取数据
*/
-(void)receiveData
{
NSLog(@"查看收到的数据");
//从数组里取出保存的数据,然后放到属性里
ble.readData = [self.array firstObject];
NSString * str = [self hexStringFromData:ble.readData];
[self.array removeObjectAtIndex:0];
NSLog(@"\n~~~~~~~~~~~~~\n收到的数据%@\n~~~~~~~~~~~~~~~~\n",str);
}
//这是下位机调用的函数
int readData(unsigned char* buf, int maxlen)
{
//在这里ble.readData还没有值,我想让他有值后再去执行下面的return什么的,请教要怎么做
buf = (unsigned char *)[ble.readData bytes];
int len = [ble.readData length];
return len;
}
奔放的野猪
9 years, 8 months ago
Answers
修改 增加successedBlock:(void (^)(int len))getDataBlock
- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic successedBlock:(void (^)(int len))getDataBlock
error:(NSError *)error
{
if (error)
{
NSLog(@"Error receiving notification for characteristic %@: %@", characteristic, error);
return;
}
else
{
[self.lock lock];
NSLog(@"\n准备查看收到的数据");
//接受的数据
NSData*receiveData= [NSData dataWithData:characteristic.value];
//处理数据
int length = .......
if(getDataBlock) {
getDataBlock(length);
}
//对存储在数组里的
[self.lock unlock];
}
}
哔。。你妹
answered 9 years, 8 months ago