gpt4 book ai didi

ios - 阻塞 for 循环,直到委托(delegate)方法被触发

转载 作者:行者123 更新时间:2023-11-29 11:48:52 26 4
gpt4 key购买 nike

我目前正在使用 CBPeripheralDelegate 在 iOS 设备和低功耗蓝牙 USB 加密狗之间交换消息。我必须实现使用串行仿真服务写入数据字节的 sendMessage: 方法。此方法必须同时发送一个 15 字节(或更少)的帧,在发送下一个之前等待来自加密狗的确认。

下面是我的代码:

- (void)sendMessage:(NSData *)message {
NSArray *chuncks = [self splitMessage:message];
for (NSUInteger i = 0; i < chunks.count; i++) {
NSData *chunk = [chunks objectAtIndex:i];
[self sendChunk:chunk withId:i ofChunks:chances.count];
// Wait for the ack to be received
}
}

- (void)sendChunk:(NSData *)chunk withId:(NSInteger)id ofChunks:(NSInteger)count {
NSMutableData *frame = [NSMutableData new];
// Here I build my frame, adding header, current chunk ID and total number of chunks, then I call...
[serialEmulationService writeValue:frame forCharacteristic:serialEmulationServiceCharacteristic type:CBCharacteristicWriteWithResponse];
}

现在的问题是:必须阻止 sendMessage: 方法中的 for 循环,直到外围设备不会收到 ack,可能会超时。这个ack是在委托(delegate)方法- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error里面收到的,所以这里我要重启for 循环先前被阻止。

针对这种特定情况的最佳做法是什么?我想使用 GCD 的信号量,但我不知道如何实现同步调用,也无法理解解释该技术的许多在线示例中的任何一个。

有人可以帮我一下吗?

最佳答案

如何完全跳过 for 循环……

@property (nonatomic) NSMutableArray *chunks;
@property (nonatomic) NSInteger chunkId;

- (void)sendMessage:(NSData *)message {
self.chunks = [[self splitMessage:message] mutableCopy];
self.chunkId = 0;

[self sendNextChunk];
}

- (void sendNextChunk {

NSData * chunk = self.chunks.firstObject;

if chunk == nil {
return
}

[self.chunks removeObjectAtIndex: 0];
[self sendChunk:chunk withId:chunkId++ ofChunks:chances.count];
}


- (void)sendChunk:(NSData *)chunk withId:(NSInteger)id ofChunks:(NSInteger)count {
NSMutableData *frame = [NSMutableData new];
// Here I build my frame, adding header, current chunk ID and total number of chunks, then I call...
[serialEmulationService writeValue:frame forCharacteristic:serialEmulationServiceCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
[self sendNextChunk];
}

关于ios - 阻塞 for 循环,直到委托(delegate)方法被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135127/

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