Basics Introduction To Using CHCSVParser

前端 未结 1 1690
暖寄归人
暖寄归人 2020-12-28 19:08

I\'m implementing CHCSVParser into my iPhone app (thanks Dave!) however I\'m really confused on how to use it. I\'ve read the read-me and searched some questions on SO but

相关标签:
1条回答
  • 2020-12-28 19:32

    I'm glad you like it :)

    Basically, CHCSVParser only parses CSV files. You give it a path to a CSV file, and it'll give you back a whole bunch of NSStrings. What you do beyond that point is entirely up to you.

    So let's say you've included a CSV file in your iOS app called "Data.csv". Here's how you'd use CHCSVParser to parse it:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"csv"];
    
    NSError *error = nil;
    NSArray *rows = [NSArray arrayWithContentsOfCSVFile:path encoding:NSUTF8StringEncoding error:&error];
    if (rows == nil) {
      //something went wrong; log the error and exit
      NSLog(@"error parsing file: %@", error);
      return;
    }
    

    At this point, rows is an array. Each element in rows is itself an array representing a single row in the CSV file. And each element of that array is an NSString.

    So let's say your CSV file looks like this:

    Barringer,Arizona,United States,Earth
    "Chicxulub, Extinction Event Crater",,Mexico,Earth
    Tycho,,,Moon
    Lonar,Maharashtra,India,Earth
    

    If you run it through the parser, you'll get back the equivalent of this:

    [NSArray arrayWithObjects:
     [NSArray arrayWithObjects:@"Barringer",@"Arizona",@"United States",@"Earth",nil],
     [NSArray arrayWithObjects:@"Chicxulub, Extinction Event Crater",@"",@"Mexico",@"Earth",nil],
     [NSArray arrayWithObjects:@"Tycho",@"",@"",@"Moon",nil],
     [NSArray arrayWithObjects:@"Lonar",@"Maharashtra",@"India",@"Earth",nil],
     nil];
    

    What you do with it then is your business. The CSV parser doesn't know anything about UITableView, so you get to take this data and re-structure it in a way that you're comfortable dealing with and that fits in to your data model.

    Also, remember that by using CHCSVParser, you agree to abide the terms under which it is made available. :)

    0 讨论(0)
提交回复
热议问题