0

I was wondering what the best way of displaying the contents of a CSV file in a UIPicker would be.

The idea is that a person picks a date range in a UIPicker and then gets a UIAlert popup based on their selection.

I know there are probably a few options. I thought there might be something simple where I can avoid making a database.

My CSV file has 4 columns. One of the columns is a date range column and is written like:

Feb 20, 1920 - Feb 7, 1921
Feb 8, 1921 - Jan 27, 1922
Jan 28, 1922 - Feb 15, 1923
Feb 16, 1923 - Feb 4, 1924
etc....

thanks for any help.

hanumanDev
  • 6,592
  • 11
  • 82
  • 146
  • I think the difficult part here is to parse all the dates, so that you can compare them to the user entered date. Doing this every time in memory may create a performance problem. On the other hand you could create an in memory representation and reuse this. How many rows does the CSV have? Do you already have a parser for that file? – tonklon Jul 08 '11 at 09:07
  • thanks for your response. there are 104 rows. the user won't enter a date, but simply scroll the uipicker to the relevant date range and then get a UIAlert with a value from another column in the same row as the date range. – hanumanDev Jul 08 '11 at 09:11

1 Answers1

2

You could build an incredibly simple CSV parser just using methods of NSString.

You can read in the contents on the CSV using

+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

You can then split the string to get an array where each object represents a line in the file using

- (NSArray *)componentsSeparatedByString:(NSString *)separator

passing @"\n" as the separator

Once you have this array, you can then loop through it and use the same method to split each line up by passing @"," as the separator (assuming your columns are comma delimited, although in your case it seems the delimeter may be something else?)

NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *rows = [contents componentsSeparatedByString:@"\n"];
for (NSString *row in rows) {
    NSArray *values = [row componentsSeparatedByString:@","];
    // do something with the values here
}
  • 1
    Given the above code, I think the column separator is likely to be @"\t" (tab), instead of @",". But otherwise this seems the way to go. – tonklon Jul 08 '11 at 09:16
  • You are correct; I've updated my code to reflect your comment. –  Jul 08 '11 at 09:20