【问题标题】:parsing text file in objective C在目标C中解析文本文件
【发布时间】:2011-09-23 10:32:36
【问题描述】:

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

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 时,即它作为单个字符串打印的文本文件的数据,所以我无法逐行获取内容请帮我解决这个问题.

【问题讨论】:

标签: iphone objective-c ios text-parsing


【解决方案1】:

改为使用:

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

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

例子:

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

另外,seperatedValues 已过度释放。第一个是用 alloc init 创建的,然后在下一行被方法componentsSeparatedByString 替换。所以第一个 od 没有被释放就丢失了,那就是泄漏。后来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);

【讨论】:

    【解决方案2】:

    您确定您的文本文件中使用的行分隔符是\n 而不是\r(或\r\n)?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多