carloe
carloe

Reputation: 1540

NSString: EOL and rangeOfString issues

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.

if([dataBuffer rangeOfString:@"\n"].location != NSNotFound) {
  NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:@"\n" withString:@"NEWLINE"];
  NSLog(@"%@", tmp);
 }

The code above outputs "...}NEWLINE{..." as expected. But if I change the @"\n" in the if-statement above to @"}\n", I get nothing.

Upvotes: 0

Views: 878

Answers (1)

user189804
user189804

Reputation:

Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of @"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.

if([dataBuffer rangeOfString:@"\n"].location != NSNotFound) {
    NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:@"\n"];

    for(NSString* oneString in JSONstrings)
    {
        // here's where you process individual JSON strings
    }
}

If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.

Upvotes: 2

Related Questions