iPhone:如何将CSV格式转换为NSData或NSString? [英] iPhone : How to convert CSV format into NSData or NSString?
问题描述
我正在制作一个需要当前股价的iPhone应用程序。
我从以下链接接收CSV格式的数据。
http:/ /finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk
可以将CSV格式转换为NSData或NSString格式?
如果是,如何将CSV格式转换为NSData格式或NSString格式?
请帮助和建议您可以采取什么措施?
感谢
不要重新发明车轮: CHCSVParser 是以Objective-C编写的本机CSV解析器。它有正确的处理引用字段,转义字符等等。它有方便的方法( + [NSArray arrayWithContentsOfCSVFile:...]
)和块文件读取,内存警告。
这里(或多或少)如何使用它。那个CSV文件是远程复杂的事情有点,但不是太多(你必须将URL的内容下载到一个字符串,然后将该字符串传递给解析器)。
#importCHCSV.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];
//你也可以: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
),
(
)
) / code>
它返回 NSArray
/ code> of NSStrings
。
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 convert the CSV format to NSData format or NSString format?
What can be done?
What can be the other alternatives for this?
Please Help and Suggest
Thanks
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
.
这篇关于iPhone:如何将CSV格式转换为NSData或NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!