Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

objective c - How to convert CSV format into NSData or NSString in iPhone?

I am making an iPhone app which requires the current Stock Prices.

I am receiving the data in CSV format from a link given below.

http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk

Is it possible to convert the CSV format to NSData or NSString format? If yes, how can I do so?

What can be the other alternatives for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't re-invent the wheel: CHCSVParser is a native CSV parser written in Objective-C. It properly handles quoted fields, escaped characters, etc. It has convenience methods (+[NSArray arrayWithContentsOfCSVFile:...]) and chunks the file reading so as not to produce low memory warnings.

Here's (more or less) how you'd use it. That the CSV file is remote complicates things a little bit, but not much (you have to download the contents of the URL into a string, and then pass that string into the parser).

#import "CHCSV.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString * csv = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://download.finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk"]];
    NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:NSUTF8StringEncoding error:nil];
    //You can also do:  rows = [csv CSVComponents];
    NSLog(@"rows: %@", rows);
    [pool drain];
    return 0;
}

This logs:

2010-12-23 09:05:44.431 CHCSVParser[99377:a0f] (
        (
        RHT,
        "46.48",
        "46.46",
        "26.51",
        "49.00"
    ),
        (
        MSFT,
        "28.23",
        "28.22",
        "22.73",
        "31.58"
    ),
        (
        ""
    )
)

It returns an NSArray of NSArrays of NSStrings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...