1

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!

Sven
  • 22,475
  • 4
  • 52
  • 71
Mikael
  • 3,572
  • 1
  • 30
  • 43
  • That's a lot things to store in RAM on a mobile device! The code that you omitted would be interesting, too. You can check your memory consumption with Instruments. – Eiko Dec 10 '10 at 09:30

2 Answers2

0

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
}
Eimantas
  • 48,927
  • 17
  • 132
  • 168
0

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.

Sven
  • 22,475
  • 4
  • 52
  • 71