Note that there are some explanatory texts on larger screens.

plurals
  1. POHow To Use the CHCSVParser class
    text
    copied!<p>I am playing around with Dave DeLong's excellent <a href="http://github.com/davedelong/CHCSVParser" rel="noreferrer">CHCSVParser</a> for Objective-C with an extremely long .CSV file and am running into some trouble using it. I would use the <code>arrayWithContentsOfCSVFile</code> method, but I'm running the code on an iPhone and parsing the whole file into memory would take more memory than is available.</p> <p>In my code below, the parser opens the document and calls the delegate methods perfectly, but where in the delegate do I stop after each line and access the data (to create and save a Core Data object to the data store)? I assume that would be in <code>- (void) parser:(CHCSVParser *)parser didEndLine:(NSUInteger)lineNumber</code>, but how do I get an <code>NSArray</code> (or whatever) of the data from the parser when it's done with the line?</p> <p>Here is my code so far:</p> <pre><code>// // The code from a method in my view controller: // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSFileManager *manager = [NSFileManager defaultManager]; NSError *err = nil; NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:&amp;err]; NSString *fileName = [fileList objectAtIndex:1]; NSURL *inputFileURL = [NSURL fileURLWithPath: [documentsDirectory stringByAppendingPathComponent:fileName]]; NSStringEncoding encoding = 0; CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVFile:[inputFileURL path] usedEncoding:&amp;encoding error:nil]; [p setParserDelegate:self]; [p parse]; [p release]; ... #pragma mark - #pragma mark CHCSVParserDelegate methods - (void) parser:(CHCSVParser *)parser didStartDocument:(NSString *)csvFile { NSLog(@"Parser started!"); } - (void) parser:(CHCSVParser *)parser didStartLine:(NSUInteger)lineNumber { //NSLog(@"Parser started line: %i", lineNumber); } - (void) parser:(CHCSVParser *)parser didEndLine:(NSUInteger)lineNumber { NSLog(@"Parser ended line: %i", lineNumber); } - (void) parser:(CHCSVParser *)parser didReadField:(NSString *)field { //NSLog(@"Parser didReadField: %@", field); } - (void) parser:(CHCSVParser *)parser didEndDocument:(NSString *)csvFile { NSLog(@"Parser ended document: %@", csvFile); } - (void) parser:(CHCSVParser *)parser didFailWithError:(NSError *)error { NSLog(@"Parser failed with error: %@ %@", [error localizedDescription], [error userInfo]); } </code></pre> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload