Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Narendar Singh

macrumors member
Original poster
Jun 22, 2012
76
0
INDIA
I have few rows in SQLite schema, I want to mail this data in CSV format from my iOS application.

How can I achieve this?

FYI my schema has following columns:
name | dob | mobile_number
 
A dumb way would be to have three arrays, one for each column.

You have to write a SQL query for each column in the table.

Then you can easily create the CSV string:

Code:
NSString *csvString = @"name, dob, mobile_number";
for (int i = 0; i < totalRows; i++) {
    csvString = [csvString stringByAppendingString:[NSString stringWithFromat:@"\n%@, %@, %@", [names objectAtIndex:i], [dobs objectAtIndex:i], [mobile_numbers objectAtIndex:i]]];
}
 
There is an NSArray method that returns all an array's components joined by a given string. If the array held one complete row, and the string is a comma, you'll get CSV (or the simple-minded version of it). The method is componentsJoinedByString:.

"Simple-minded" means it won't account for quotes or commas in a component string. So if one of the strings in the array was @"Oops, it broke", then you'd end up with a comma where it shouldn't be.

As with many things in programming, a better CSV generator can be built up from smaller simpler parts. If the OP isn't interested in doing that, then like many things in programming, a little searching can often find someone else's code. For example, google search terms: CSV objective-C or cocoa csv
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.