无法使用CHCSV解析器解析csv文件

时间:2015-02-28 09:22:29

标签: ios objective-c parsing csv

我正在使用CHSV解析器来解析csv文件,但在控制台中什么都没有,下面的代码用于解析csv。我导入了CHSV头文件并提到CHCSVParserDelegate,即使我也检查了csv文件名

 CHCSVParser *parser=[[CHCSVParser alloc] initWithContentsOfCSVFile:[NSHomeDirectory() stringByAppendingPathComponent:@"gapunditprogeorgiastatehouse.csv"] delimiter:','];
  parser.delegate=self;
  [parser parse];

-(void) parserDidBeginDocument:(CHCSVParser *)parser
{
  currentRow = [[NSMutableArray alloc] init];
}

-(void) parserDidEndDocument:(CHCSVParser *)parser
{
  for(int i=0;i<[currentRow count];i++)
  {
    NSLog(@"%@          %@          %@",[[currentRow objectAtIndex:i] valueForKey:[NSString stringWithFormat:@"0"]],[[currentRow objectAtIndex:i] valueForKey:[NSString stringWithFormat:@"1"]],[[currentRow objectAtIndex:i] valueForKey:[NSString stringWithFormat:@"2"]]);
  }
}

- (void) parser:(CHCSVParser *)parser didFailWithError:(NSError *)error
{
  NSLog(@"Parser failed with error: %@ %@", [error localizedDescription], [error userInfo]);
}

-(void)parser:(CHCSVParser *)parser didBeginLine:(NSUInteger)recordNumber
{
  dict=[[NSMutableDictionary alloc]init];
}

-(void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex
{
  [dict setObject:field forKey:[NSString stringWithFormat:@"%d",fieldIndex]];
}

- (void) parser:(CHCSVParser *)parser didEndLine:(NSUInteger)lineNumber
{
  [currentRow addObject:dict];
  dict=nil;
}

1 个答案:

答案 0 :(得分:1)

我的csv文件有点像这样

India;26;F;New Delhi;20000;NO;0;2009
France;30;M;New York;20000;NO;1;2009
Germany;24;F;New York;20000;NO;0;2009
Mexico;28;M;New Delhi;20000;NO;1;2009

要阅读此csv文件,我使用了这种方法:

NSMutableArray *arrTitle=[[NSMutableArray alloc]init];

NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *linesArray=[fileDataString componentsSeparatedByString:@"\n"];

 [linesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
  {
     NSArray *columnArray=[obj componentsSeparatedByString:@";"];
     [arrTitle addObject:[columnArray objectAtIndex:0]];

 }];


NSLog(@"%@",arrTitle);

此处path是您的csv文件路径。

输出是:

(
 India,
 France,
 Germany,
 Mexico
)
相关问题