【问题标题】:Contents of Plist file getting deletedPlist文件的内容被删除
【发布时间】:2013-05-31 23:58:25
【问题描述】:

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

这是我的名为 sample.plist 的 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];
}

【问题讨论】:

    标签: ios objective-c plist


    【解决方案1】:

    我遇到了类似的问题,也许这个解决方案会有所帮助。与其在 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 是只读的。

    【讨论】:

      【解决方案2】:

      您可以在 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;
      

      }

      【讨论】:

      • 非常感谢您的建议
      • @user2440960 很高兴为您提供帮助。如果有帮助,请接受答案。快乐编码:)
      猜你喜欢
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2015-02-14
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多