ios解析csv 笔记

2 篇文章 0 订阅
0 篇文章 0 订阅

在xcode中, csv格式的文件是一种占内存很小的文本文档,它的特点:

     (1)开头是不留空  ,以行为单位。
    (2)每条记录占一行,以逗号为分隔符。列为空也要表达其存在。
    (3)可含或不含列名,如果含列名则居文件第一行。
    (4)一行数据不跨行,无空行。
    (5)字段中包含有逗号符,该字段必须用双引号括起来。
    (6)字段中包含有换行符,该字段必须用双引号括起来。
    (7)字段前后包含有空格,该字段必须用双引号括起来。( a b c ==> "a b c")
    (8)字段中的双引号,用两个双引号表示。( 我说:"abc"。 ==> 我说:""abc""。 )
    (9)字段中如果有双引号,该字段必须用双引号括起来。( 我说:"abc"。 ==> "我说:""abc""。"

第三方库:

CHCSVParser。https://github.com/davedelong/CHCSVParser

您可以初始化分析器与 CSV 文件的路径 (假设你有 CHCSVParser * _parser 实例变量):

NSString *filePath = ...; // the path to your CSV file
_parser
= [[CHCSVParser alloc] initWithContentsOfCSVFile:filePath];
_parser
.delegate = self;
[_parser parse];

然后你应该使用三个委托方法的组合自定义解析器,使它适合您的需要︰

- (void)parser:(CHCSVParser *)parser didBeginLine:(NSUInteger)recordNumber
{
   
// Only parse the fields on lines 41 to 50
   
// _shouldParseLine is an ivar that is set to YES
   
// only when the fields inside the following line or lines
   
// should be parsed.
   
if (recordNumber == 41) {
        _shouldParseLine
= YES;
   
}
}

- (void)parser:(CHCSVParser *)parser didEndLine:(NSUInteger)recordNumber
{
   
if (recordNumber == 50) {
       
// The parser has finished parsing the 50th line
       
// We're done, cancel any further parsing.
       
// It is not necessary to set _shouldParseLine to NO,
       
// since the parser is killed here and the didReadField
       
// delegate method will not be called again.
       
[parser cancelParsing];
   
}
}

- (void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex
{
   
if (_shouldParseLine == YES) {
       
// Here are your fields.
       
// The field at index 0 consists of the text
       
// before the comma, the field at index 1
       
// consists of the text after the comma.
   
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值