创建一个plist文件

时间:2011-02-16 14:12:50

标签: iphone plist

我想在一个plist上写一个数组,当我在文档文件夹中手动创建plist时,这个工作正常。

但是当我检查plist是否存在以及是否从主束中的plist创建它时没有任何事情发生.....

我是按照Property List Programming Guide编写的。

NSString *plistRootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [plistRootPath stringByAppendingPathComponent:@"list.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {

    plistPath = [[NSBundle mainBundle] pathForResource:@"list" ofType:@"plist"];

}

我错过了什么?

编辑:

我在一个单独的应用程序中尝试了该功能并且它有效。 所以我再试一次:

 NString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
 NSString *plistPath = [rootPath stringByAppendingPathComponent:@"list.plist"]; 

self.ListArray = [NSMutableArray arrayWithContentsOfFile:plistPath]; 
NSLog(@"preSave: %@", [ListArray count]);
NSLog(@"%@", plistPath);

和日志说:

2011-02-16 16:54:56.832 ListApp[3496:207] .../Library/Application Support/iPhone Simulator/4.0.2/Applications/267F55E4-A46A-42E0-9E1C-EAF26846F75F/Documents/list.plist

但是Dir中没有文件。!

2 个答案:

答案 0 :(得分:2)

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

filePath=[DocPath stringByAppendingPathComponent:@"AlarmClock.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"AlarmClock" ofType:@"plist"];
    NSLog(@"file path: %@",filePath);
    NSDictionary *info=[NSDictionary dictionaryWithContentsOfFile:path];
    [info writeToFile:filePath atomically:YES];
}

// * * *试试这个......

答案 1 :(得分:0)

我在另一个mac上尝试了代码并且在那里工作它是同一个项目。

任何人都可以解释为什么plist是在一个mac上创建的而不是在另一个mac上创建的?

在IPhone上也没有写过plist?

我猜两种情况都是因为我写入plist的数组是空的:

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"list.plist"];  
NSMutableArray *currentArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];   
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
            [selectet valueForKey:NAME], @"name",
            nil];   

NSLog(@" DIC. : %@", dictionary);
[currentArray addObject:[dictionary copy]];
NSLog(@" %@", currentArray);
[currentArray writeToFile:plistPath atomically:YES];
[currentArray release];

字典有条目但currentArray是空的.... 它仍然适用于一台Mac。但不是在另一方和iPhone上。

修改:

由于某种原因它再次起作用。

为了确保我从文档文件夹中删除了plist并清除了所有目标。

现在问题和以前一样,我只能在写字典的时候编写plist但是我只能保存最后一个。 阅读plist也行不通。

任何人都可以告诉我为什么会发生这种情况以及如何解决它?

编辑2:

我发现了问题:因为当我用字典向plist编写数组时,X-Code不会创建plist。当我将字典写入plist时,X-Code创建了plist但是带有字典Root所以我不能把数组写入它,我也无法在数组中读取它......

我在Resources文件夹中创建了一个带有Array Root的plist,并在它不存在时将其复制到文档文件夹中,现在它可以工作.....

如此轻松的事情会让你如此头疼并不令人惊讶

相关问题