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

ios - writetofile automatically is not working

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

并调用下面的方法

-(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];

}

}

dataArray 是

但是[dataArray writeToFile:destPath atomically:YES]; return没有

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

看起来 dataArray 包含一个或多个不是 属性 列表对象的对象,(更具体地说 NSNull 个对象)。 writeToFile:atomically: 将 return 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];