簡體   English   中英

阻塞 for 循環直到委托方法被觸發

[英]Block a for loop until a delegate method gets fired

我目前正在使用CBPeripheralDelegate在 iOS 設備和藍牙低功耗 USB 加密狗之間交換消息。 我必須實現使用串行仿真服務寫入數據字節的sendMessage:方法。 此方法必須在當時發送 15 個字節(或更少)的幀,在發送下一個之前等待來自加密狗的 ack。

下面是我的代碼:

- (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 是在委托方法中收到的- (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];
}

方法是使用Notification 創建separate method來運行您的for loop 此方法將觀察Notification ,在delegate方法內發布Notification sendMessage:繼續將消息添加到屬性中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM