gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:27:06 25 4
gpt4 key购买 nike

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

为什么没有效果?我该如何解决?

最佳答案

看起来 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com