0

我不知道如何命名,更不用说解释清楚了,但它就在这里。

我目前有这个方法:

- (void) receivedData:(NSString *)data {
}

它在读取串行数据时触发。串行数据输入为:<DMX>255,23,1,4,6</DMX>问题是,它不是作为一个统一的字符串输入。它是碎片化的。比如, <DM, X>255, ,23,1,4,, 等等。它是随机的,所以我无法追踪它。有时它会发送整个内容,有时它会一次发送几个字符。就是这样。

如何,在我的代码中,我可以等待整个事情进来(从开始到<DMX>结束</DMX>)然后创建一个 NSString?也许随着数据进来,存储碎片,等待结束</DMX>,然后将它们组合在一起?

谢谢!

4

1 回答 1

1
  1. 如果您正在解析 XML,并且可以选择使用 XML 解析器 - 使用它(iOS/OSX 中有内置的 XML 解析器,以及许多其他选项)。

  2. 但是,如果您决定对此进行编码...

创建NSMutableString ivar并在接收数据时继续向其添加 ( appendString)... 然后跟踪您是否已经遇到开始/结束标签...

沿着这些路线的东西..

MyClass.h

@interface Myclass : NSObject
{
    NSMutableString *buffer, *tmpBuffer;
    int status; // 0=waiting for <DMX>, 1=recording, 2=done
}

MyClass.m

-(id) init {
  if(self = [super init]) {
    buffer = [[NSMutableString alloc] init];
    tmpBuffer = [[NSMutableString alloc] init];
    status = 0;
  }
  return self;
}

-(void) receivedData:(NSString *)data {
  if(status == 2) return; // already done

  // status=0 means we are still looking for start tag
  if(status == 0) {
    // add new data to last examined chunk (if any)
    [tmpBuffer appendString:data];

    // try to locate the open tag inside the tmpBuffer
    NSRange range = [tmpBuffer rangeForString:@"<DMX>" options:NSCaseInsensitiveSearch];

    // if found, store the portion after the start tag into buffer
    if(range.location != NSNotFound) {
      range.length = [tmpBuffer length] - range.location + 5; // 5 is length of start tag...
      [buffer setString:[tmpBuffer substringWithRange:range]];
      status = 1; // set status to 1 so we know recording started
    } else {
      // store last examined chunk
      [tmpBuffer setString:data];
    }
  }
  else {
    [buffer appendString:data];
    NSRange range = [buffer rangeForString:@"</DMX>" options:NSCaseInsensitiveSearch];
    if(range.location != NSNotFound) {
      range.length = [buffer length] - range.location;
      [buffer deleteCharactersInRange:range];
      status = 2;
    }
  }
}

-(void) dealloc {
  [buffer release];
  [tmpBuffer release];
  [super dealloc];
}
于 2012-12-01T23:39:05.183 回答