【问题标题】:ios - writetofile automatically is not workingios - writetofile 自动不起作用
【发布时间】:2015-07-26 05:03:09
【问题描述】:

我制作了这样的 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 writeToFile:destPath atomically:YES];返回否

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

【问题讨论】:

    标签: ios objective-c nsdictionary plist writetofile


    【解决方案1】:

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

    文档提到以下关于 writeToFile:atomically:

    此方法在写出文件之前递归地验证所有包含的对象都是属性列表对象,如果所有对象都不是属性列表对象,则返回 NO,因为生成的文件不是有效的属性列表。

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

    例如。

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-06
      • 2016-11-28
      • 1970-01-01
      • 2012-10-06
      • 2019-03-09
      • 1970-01-01
      • 2013-01-29
      • 2014-03-28
      • 1970-01-01
      相关资源
      最近更新 更多