从用户文档而不是NSBundle访问Plist

时间:2014-07-31 14:50:26

标签: ios objective-c xcode plist nsbundle

您好我有以下代码,它完美无缺,它会找到Plist,并将NSDictionary分配给名为landingSites的NSArray。唯一的问题是我希望用户能够添加网站,因此需要将Plist存储在用户文档中而不是NSBundle

plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
dictionaryKeys = [newDictionary allKeys];
self.landingSites = [dictionaryKeys sortedArrayUsingSelector:@selector(compare:)];
self.dictionaryFromPlist = newDictionary;

[Picker selectRow:0 inComponent:0 animated:NO];

for(NSString *parent in dictionaryKeys) 
{
    NSDictionary *parentData = [dictionaryFromPlist objectForKey:parent];
    NSArray *child = [parentData objectForKey:@"Name"];
    NSLog(@"%@", child);
}

到目前为止,我已经生成了下面的代码,但每当我运行程序时,if语句总是执行,好像plist in从未复制到用户文档。此外,我不知道如何将NSDictionary内容附加到我的landingSites数组,就像我上面所做的那样。请帮忙

 (void) viewDidLoad {
        [super viewDidLoad];
        NSError *error;
        NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,  NSUserDomainMask,YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if (![fileManager fileExistsAtPath:path]) {
            NSLog(@"copying database to users documents");
            NSString *pathToSettingsBundle = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
            [fileManager copyItemAtPath:pathToSettingsBundle toPath:path error:&error];
        }
        else{
            NSLog(@"users database already configured");
        }

1 个答案:

答案 0 :(得分:0)

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,  NSUserDomainMask,YES);

NSDocumentationDirectory错了。您正在寻找NSDocumentDirectoryNSLibraryDirectory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];