【问题标题】:modifying a plist is not working修改 plist 不起作用
【发布时间】:2011-06-16 07:57:10
【问题描述】:

我必须修改与捆绑包一起存储的 plist 文件中的 BOOL 值。我能够访问我必须修改的字典。从 nslogging 我可以看到字典已更新为新值,但问题是当我检查捆绑中的 plist 时,它没有被修改。任何关于它为什么不更新 plist 的线索

  NSString* plistPath = nil;
        NSFileManager* manager = [NSFileManager defaultManager];
        if (plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"TopicsList.plist"]) 
        {
            if ([manager isWritableFileAtPath:plistPath]) 
            {
                NSMutableArray* dictarrays = [NSMutableArray arrayWithContentsOfFile:plistPath];
                NSMutableDictionary *dict=[dictarrays objectAtIndex:indexPath.row];
                NSLog(@"%@ ",dict );

                [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"];

                NSLog(@"%@ ",dict );
                [dict writeToFile:plistPath atomically:NO];
                    NSLog(@"%@ ",dict );
                [manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:&error];
            }
        }

【问题讨论】:

    标签: iphone objective-c ios plist


    【解决方案1】:

    plist 是您资源的一部分吗?不确定我们是否可以在那里编辑 plist。将 plist 复制到应用的 Documents 文件夹并在那里更新。

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"TopicsList.plist"];
    
    success = [fileManager fileExistsAtPath:plistPath];
    if(!success){
        //file does not exist. So look into mainBundle
        NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TopicsList.plist"];
        success = [fileManager copyItemAtPath:defaultPath toPath:plistPath error:&error];
    }
    

    现在,无论您需要对 plist 进行什么更改或从 plist 中读取数据,都可以从 Documents 文件夹中的副本中读取它。

    【讨论】:

    • 和@Nayefc 这意味着我应该从 xcode 中删除我的 plist 的引用并将 plist 保存在我的项目文件夹中?
    • 保留它。在应用程序启动时,将 plist 从您的包中复制到您的应用程序的 Document 文件夹(如果它尚不存在)。用相关的代码更新我的答案(应该在 application:didFinishLaunchingWithOptions:
    【解决方案2】:

    您必须将您的 plist 存储在文档目录中。之后,您还必须在离开应用程序时保存 plist。否则,plist 在主包中,无法修改。

    【讨论】:

      【解决方案3】:

      有什么错误

      检查

      NSError *error = nil
      [dict writeToFile:plistPath atomically:YES encoding:NSASCIIStringEncoding error:&error];
      
      if (error) {
        NSLog(@"Error: %@", [error description]);
      } else {
      NSLog(@"Success");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 2018-10-28
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多