如何在iPhone中将CSV格式转换为NSData或NSString? [英] How to convert CSV format into NSData or NSString in iPhone?

查看:118
本文介绍了如何在iPhone中将CSV格式转换为NSData或NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作需要当前股票价格的iPhone应用程序。

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

我从下面给出的链接收到CSV格式的数据。

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

是否可以转换CSV格式到NSData或NSString格式?如果是,我该怎么办呢?

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?

推荐答案

不要重新发明轮子: CHCSVParser 是一个原生的CSV解析器用Objective-C编写。它正确处理带引号的字段,转义字符等。它有方便的方法( + [NSArray arrayWithContentsOfCSVFile:...] )并将文件读取块,以免产生低记忆警告。

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.

这里(或多或少)你如何使用它。 CSV文件是远程的,使事情变得复杂,但不多(你必须将URL的内容下载到字符串中,然后将该字符串传递给解析器)。

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;
}

此日志:

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"
    ),
        (
        ""
    )
)

它返回 NSArray NSArrays of NSStrings

这篇关于如何在iPhone中将CSV格式转换为NSData或NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆