0

txt ファイルを 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」とアドレスの後に取得する方法....?

4

1 に答える 1

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 を作成する必要があります。これは、ファイル内のデータの順序がわかっていること、およびその順序が一貫していることを前提としています。

于 2012-08-26T20:07:24.850 に答える