Plist文件的内容被删除

时间:2013-05-31 15:34:29

标签: ios objective-c plist

我正在尝试在存储在bundle中的plist中保存name和num,它正在被正确保存,但问题是,一旦我再次执行我的应用程序,我就无法检索存储在plist中的先前数据。

这是我的plist名为sample.plist的代码,两个texfields名称,数字:

-(void)viewdidload
{
    [super viewdidload];
    self.path=[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];
    self.dictionary=[[NSMutabledictionary alloc] initWithContentsOfFile:self.path];
}

-(IBAction)save
{
    if(self.dictionary==nil) {
        self.dictionary=[[NSMutabledictionary alloc] 
        initWithObjectsAndKeys:self.name.text,self.number.text,nil];
    } else {
        self.dictionary=[NSMutabledictionary  dictionaryWithContentsofFile:self.path];
        [self.dictionary setobject:self.name.text forKey:self.number.text];
    }

    [self.dictionary writetofile:self.path];
}

2 个答案:

答案 0 :(得分:0)

您可以在SO中找到与此问题相关的许多问题。您的plist在应用程序包中是一个非常简单的问题,它是一个只读信息。

如果要编辑内容,请在第一次访问plist时将plist移动​​到文档目录。因此,始终将该路径用于所有读/写操作。

每当您需要plist的路径时,请使用以下方法

- (NSString *)savedPlistPath{

NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                          NSUserDomainMask,
                                                          YES)[0];

NSString *filePath = [documents stringByAppendingPathComponent:@"sample.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {

    NSString *bundleFilePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];
    [fileManager copyItemAtPath:bundleFilePath toPath:filePath error:nil];

}
return filePath;

}

答案 1 :(得分:0)

我有类似的问题,也许这个解决方案可能有所帮助。不是在xcode中创建plist文件并将其推送到设备,而是在文档目录中写入一个新文件。

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
self.filePath = [documentDirectory stringByAppendingPathComponent:@"sample.plist"];
[self.dictionary writeToFile:self.filePath atomically:YES];

正如@Anupdas指出的那样,捆绑中的plist是只读的。

相关问题