以编程方式在plist文件中添加索引

时间:2013-04-25 12:35:34

标签: ios xcode arrays indexing plist

我正在以编程方式创建一个plist文件直接到文档目录。这是我的代码..

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myList.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"myList.plist"] ];
}
NSMutableArray *data ;
if ([fileManager fileExistsAtPath: path])
{
    data = [[NSMutableArray alloc] initWithContentsOfFile: path];

}
else
{
    // If the file doesn’t exist, create an empty dictionary
    data = [[NSMutableArray alloc] init];
}
data = [[NSMutableArray  alloc] initWithCapacity:5];
[data addObject:value1];
[data addObject:value2];
[data addObject:value3];

它使用这种格式创建plist文件..

<array>
        <string>1</string>
        <string>2</string>
        <string>3</string>
</array>

现在,我想为它添加另一个索引,例如

<array>
        <string>1</string>
        <string>2</string>
        <string>3</string>
</array>
<array>
        <string>11</string>
        <string>22</string>
        <string>33</string>
</array>  

如何在plist文件中以编程方式添加索引?
任何帮助或建议将不胜感激!

谢谢

2 个答案:

答案 0 :(得分:4)

尝试

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myList.plist"];

NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile: path];
if (!data) {
    data = [NSMutableArray array];
}

[data addObject:@[value1,value2,value3]];

[data writeToFile:path atomically:YES];

答案 1 :(得分:1)

你应该将你的plist组织成字典。对应每个键,您可以存储数组对象。这很容易。将数组存储到NSDictionary中,并使用正确的键作为索引号。然后把那个字典弄到了plist

<dict>
  <key>0</key>
  <array>
      <string>1</string>
      <string>2</string>
      <string>3</string>
  </array>
  <key>1</key>
  <array>
      <string>11</string>
      <string>22</string>
      <string>33</string>
  </array>
</dict>