2012-08-26 42 views
0

如何解析一個txt文件到NSDictionary?解析文件到NSDictionary

我的文件看起來像

JACK - (mr) - address 
99000 - City 
Phone : 09 93 81 48 51 
Website 

這是我的代碼:

NSString *file = [[NSBundle mainBundle]pathForResource:@"MyFile" ofType:@"txt"]; 
NSError *error; 

NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:&error]; 

NSArray * testArray = [[NSArray alloc] init]; 
testArray = [text componentsSeparatedByString:@" \n"]; 

NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
for (NSString *s in testArray) 
{ 
    NSArray *arr = [s componentsSeparatedByString:@" -"]; 
    [dict setObject:[arr objectAtIndex:0] forKey:@"name"]; 
    NSLog(@"Dictionary: %@", [dict description]); 
} 

和我的NSLog給我:

Dictionary: { 
     name = "JACK"; 
} 

如何解析文件的其餘部分以獲取「mr」後的地址....?

回答

0

從您發佈的代碼看來,您只是向arr數組中的第一個元素詢問arr。試試這個:

int i= 0; 
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
for (NSString *s in testArray) 
{ 
    NSArray *arr = [s componentsSeparatedByString:@" -"]; 
    for(NSString * pstrSubComponent in arr) 
    { 
      [dict setObject:pstrSubComponent forKey:paKeysArray[i++]]; 
    } 
} 

NSLog(@"Dictionary: %@", [dict description]); 

你必須使用你期望在你的文件中使用的所有鍵的paKeysArray。這假定你知道文件中數據的順序,並且它是一致的。