开发者

NSScanner vs. componentsSeparatedByString

I have a large text file (about 10 MB). In the text file there are values like (without the empty lines between the rows, I couldn't format it here properly):

;string1;stringValue1;

;string2;stringValue2;

;string3;stringValue3;

;string4;stringValue4;

I'm parsing all the 'stringX' values to an Array and the 'stringValueX' to another string, using a pretty ugly solution:

  words = [rawText componentsSeparatedByString:@";"];
  NSEnumerator *word = [words objectEnumerator];

  while(tmpWord = [word nextObject]) {

   if ([tmpWord isEqualToString: @""] || [tmpWord isEqualToString: @"\r\n"] || [tmpWord isEqualToString: @"\n"]) {
    //   NSLog(@"%@*** NOTHING *** ",tmpWord);

   }else { // here I add tmpWord the arrays...

I've tried to do this using NSScanner by following this example: http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data

But I received memory warnings and then i开发者_JAVA百科t all crashed.

Shall I do this using NSScanner and if so, can anyone give me an example of how to do that?

Thanks!


In most cases NSScanner is better suited than componentsSeparatedByString:, especially if you are trying to preserve memory.

Your file could be parsed by a loop like this:

while (![scanner isAtEnd]) {
   NSString *firstPart = @"";
   NSString *secondPart = @"";

   [scanner scanString: @";" intoString: NULL];
   [scanner scanUpToString: @";" intoString: &firstPart];

   [scanner scanString: @";" intoString: NULL];
   [scanner scanUpToString: @";" intoString: &secondPart];

   [scanner scanString: @";" intoString: NULL];

   // TODO: add firstPart and secondPart to your arrays
}

You probably need to add error-checking code to this in case you get an invalid file.


You should use fast enumeration. It's far better than the one using objectEnumerator. Try this

for (NSString *word in words) {
    // do the thing you need
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜