ios - 自动写入文件不起作用

标签 ios objective-c nsdictionary plist writetofile

我制作了这样的 UMsgs.plist 文件

enter image description here

并调用下面的方法

-(void) checkIsChangedUMsg
{
    BOOL isNewMsg = NO;

    NSString *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destPath = [destPath stringByAppendingPathComponent:@"UMsgs.plist"];

// If the file doesn't exist in the Documents Folder, copy it.
    NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:destPath]) {
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"UMsgs" ofType:@"plist"];
    [fileManager copyItemAtPath:sourcePath toPath:destPath error:nil];
}

// Load the Property List.
   NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:destPath];

   for( int i = 0; i < [dataArray count] ;i++)
  {
    NSString * oldMessengerID = [dataArray[i] objectForKey:@"messengerid"];
    NSString * oldMessageCount = [dataArray[i] objectForKey:@"messageCount"];

    NSString * newMessengerID = [UMsgsInfoArray[i] objectForKey:@"messengerid"];
    NSString * newMessageCount = [UMsgsInfoArray[i] objectForKey:@"messageCount"];

    if( !([oldMessengerID isEqualToString:newMessengerID] && 
          [oldMessageCount isEqualToString:newMessageCount]) )
    {
        NSDictionary * newDict = [[NSDictionary alloc] initWithObjectsAndKeys:newMessageCount,@"messageCount",newMessengerID,@"messengerid",nil];
        dataArray[i] = newDict;
        isNewMsg = YES;
    }

  }

if(isNewMsg)
{
   BOOL success =  [dataArray writeToFile:destPath atomically:YES];

}

}

数据数组是

enter image description here

但是 [dataArray writeToFile:destPathatomically:YES];返回NO

为什么不起作用?我该如何解决它?

最佳答案

看起来dataArray包含一个或多个不是属性列表对象的对象,(更具体地说是NSNull对象) 。如果是这种情况,writeToFile:atomically: 将返回 NO

文档提到了以下有关 writeToFile:atomically:

This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

此外,您可能想尝试制作 NSArray 的可变副本,在尝试写入文件之前先做一些事情,然后制作不可变的副本。

例如。

// Load the Property List.

NSMutableArray *dataArray = [[[NSArray alloc] initWithContentsOfFile:destPath] mutableCopy];

并在写入之前使其不可变-

BOOL success =  [[dataArray copy] writeToFile:destPath atomically:YES];

关于ios - 自动写入文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31633812/

相关文章:

ios - didSelectViewController 在某些情况下不会被调用

ios - 如何在用户触摸屏幕后延迟代码运行

objective-c - 设置相对于设备尺寸的自动布局约束

ios - 用 sizeWithAttributes 替换弃用的 sizeWithFont

ios - 如何从 NSDictionary 中删除空值

ios - 将动态创建的 UIView 置于 Storyboard 中的 UILabel 的中心无法正常工作

ios - 在 Swift 3 中使用 NSCoder 编码/解码日期?

iphone - 如何将压缩的声音文件转换为未压缩的文件

ios - 使用 GooglePlus 类从 NSDictionary 获取键值

objective-c - 为什么我不应该使用[NSDictionary objectForKey:]?