这不是 runLoop 或 ExternalAccessories 问题。这是一个日常的 OOP 问题。
最好的方法是创建一个可以写入 outputStream 并等待响应的通信对象。使用@protocols 来做到这一点!(事件监听器驱动的过程)
试试这个:
首先,您必须将输入/输出流附加到 runLoop:
[[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session inputStream] open];
[[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session outputStream] open];
成为他们的代表:
[[session outputStream] setDelegate:self];
[[session inputStream] setDelegate:self];
一旦你成为委托,你必须实现这个方法:
-(void)stream:handleEvent:{};
这是将数据写入流的命令:
/* data is a NSData containing data to transmit. */
[[session outputStream] write:(uint8_t *)[data bytes] maxLength:[data length]];
这是一个示例代码,(一旦您创建了会话,而我们期望的答案是一个字节):
在 Comm.h 中:
/* Define your protocol */
@protocol CommDelegate <NSObject>
-(void)byteReceived: (char) byte;
@end
@interface Comm <NSObject> {
[...]
id<CommDelegate> delegate;
}
@end
@property (nonatomic, retain) id<CommDelegate> delegate;
在 Comm.m 中:
@implementation Comm
[...]
-(id)init {
[...]
delegate = nil;
[...]
}
-(void)write: (NSData *) data {
[[session outputStream] write:(uint8_t *)[data bytes] maxLength:[data length]];
}
-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)_event {
switch (_event)
{
case NSStreamEventHasBytesAvailable:
/* This part will be executed every time your rx buffer contains at least 1 byte */
switch(state) {
uint8_t ch;
/* Read byte per byte */
[stream read:&ch maxLength:1];
/* now ch contains a byte from your MFI device
** and 'read' function decrease the length of the rx buffer by -1 */
/* Now you can notify this to the delegate
*/
if(self.delegate != nil)
[delegate byteReceived: ch];
}
break;
}
}
your_app_controller.h:
@interface MyApp : UIViewController <CommDelegate> {
Comm comm;
}
@end
your_app_controller.m:
@implementation MyApp
-(id)init {
[...]
comm = [[Comm alloc] init];
[comm setDelegate: self]; /* Now your thread is listening your communication. */
}
-(void)write {
byte out = 'X';
[comm write: [NSData dataWithBytes: &out length: 1]];
}
-(void)bytereceived:(char)reply {
if(reply == 'Y') {
[self write];
//[self performSelectorInBackground:@selector(write) withObject:nil]; IT'S BETTER!!!
}
}
@end
希望这可以帮助!