簡體   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