简体   繁体   中英

ios - writetofile automatically is not working

I made UMsgs.plist file like this

在此处输入图片说明

and call below method

-(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 is

在此处输入图片说明

but [dataArray writeToFile:destPath atomically:YES]; return NO

why it doesn't work? how I fix it?

It looks as though dataArray contains one or more objects that are not property list objects, ( more specifically NSNull object(s) ). writeToFile:atomically: will return NO if this is the case.

Documentation mentions the following about 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.

Additionally you may want to try making a mutable copy of an NSArray, do stuff then make an immutable copy before attempting to write to file.

eg.

// Load the Property List.

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

and make immutable before writing-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM