NSScanner vs. componentsSeparatedByString

匆匆过客 提交于 2019-12-11 13:25:04

问题


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 it all crashed.

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

Thanks!


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/4407211/nsscanner-vs-componentsseparatedbystring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!