繁体   English   中英

解析目标C中的文本文件

[英]parsing text file in objective C

我正在尝试解析保存在doc dir下面的文本文件show是它的代码

NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDirPath=[filePaths objectAtIndex:0];
NSString *filePath=[docDirPath stringByAppendingPathComponent:@"SKU.txt"];
NSError *error;
NSString *fileContents=[NSString stringWithContentsOfFile:filePath];
NSLog(@"fileContents---%@",fileContents);   
if(!fileContents)
NSLog(@"error in reading file----%@",error);
NSArray *values=[fileContents componentsSeparatedByString:@"\n"];
NSLog(@"values-----%@",values);

NSMutableArray *parsedValues=[[NSMutableArray alloc]init];
for(int i=0;i<[values count];i++){
    NSString *lineStr=[values objectAtIndex:i];
    NSLog(@"linestr---%@",lineStr);
    NSMutableDictionary *valuesDic=[[NSMutableDictionary alloc]init];
    NSArray *seperatedValues=[[NSArray alloc]init];
    seperatedValues=[lineStr componentsSeparatedByString:@","];
    NSLog(@"seperatedvalues---%@",seperatedValues);
    [valuesDic setObject:seperatedValues forKey:[seperatedValues objectAtIndex:0]];
    NSLog(@"valuesDic---%@",valuesDic);
    [parsedValues addObject:valuesDic];
    [seperatedValues release];
    [valuesDic release];
}
NSLog(@"parsedValues----%@",parsedValues);
NSMutableDictionary *result;
result=[parsedValues objectAtIndex:1];
NSLog(@"res----%@",[result objectForKey:@"WALM-FT"]);

我面临的问题是,当我尝试打印lineStr即文本文件的数据时,它打印为单个字符串,因此我无法逐行获取内容,请帮我解决此问题。

而是使用:

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

它涵盖了几个不同的换行符。

例:

NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
    // Parsing code here
}

seperatedValues被过度释放。 第一个是使用alloc init创建的,然后在下一行中由方法componentsSeparatedByString替换。 所以第一个没有被释放就失去了,这就是泄漏。 之后由componentsSeparatedByString创建的seperatedValues被释放,但是它已经被componentsSeparatedByString自动释放为过度释放;

使用ARC(自动参考计数)解决所有保留/释放/自动释放问题。

这是一个使用便捷方法并省略过度释放的版本:

NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
    NSArray *seperatedValues = [lineStr componentsSeparatedByString:@","];
    NSString *key = [seperatedValues objectAtIndex:0];
    NSDictionary *valuesDic = [NSDictionary dictionaryWithObject:seperatedValues forKey:key];
    [parsedValues addObject:valuesDic];
}
NSLog(@"parsedValues---%@",parsedValues);

你肯定在文本文件中使用的在线分离器\\n ,而不是\\r (或\\r\\n )?

问题可能来自于此,解释了为什么您无法将文件拆分为不同的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM