我制作了这样的 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: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/