加入不完整的字符串Objective-c

时间:2012-12-01 23:36:10

标签: objective-c string serial-port

我不确定如何标题,更不用说解释一下了,但在这里。

我目前有这种方法:

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

在读取串行数据时触发。串行数据以:<DMX>255,23,1,4,6</DMX>问题出现,它不是作为一个统一字符串出现的。它有碎片。比如<DMX>255,23,1,4,等。它是随机的,所以我无法跟踪它。有时它发送整个事物,其他人一次发送每个字符。就是这样。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

  3. 创建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];
    }