gpt4 book ai didi

iphone - 如何在Objective-C中将键值对添加到plist文件

转载 作者:行者123 更新时间:2023-12-01 19:17:36 26 4
gpt4 key购买 nike

我正在使用iPhone应用程序,需要使用Objective-C将新的键值对添加到现有的plist文件中。到目前为止,这是我尝试过的:

NSString *myFile=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];

dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
[dict setObject:textContent forKey:keyName];
[dict writeToFile:myFile atomically:YES];

但是,当我这样做时,它不会将其写入文件。我仅看到基于更改键的值或添加到另一个键的资源。还有另一种方法可以做到这一点吗?

感谢您的时间

最佳答案

您无法在捆绑包中进行任何更改。因此,您要做的就是将.plist文件复制到您的documents目录中,并在那里进行操作。

遵循以下原则:

//check for plist
//Get documents directory's location
NSArray*docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*filePath=[docDir objectAtIndex:0];
NSString*plistPath=[filePath stringByAppendingPathComponent:@"Favourites.plist"];

//Check plist's existance using FileManager
NSError*err=nil;
NSFileManager*fManager=[NSFileManager defaultManager];

if(![fManager fileExistsAtPath:plistPath])
{
//file doesn't exist, copy file from bundle to documents directory

NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
[fManager copyItemAtPath:bundlePath toPath:plistPath error:&err];
}

//Get the dictionary from the plist's path
NSMutableDictionary*plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//Manipulate the dictionary
[plistDict setObject:textContent forKey:keyName];
//Again save in doc directory.
[plistDict writeToFile:myFile atomically:YES];

关于iphone - 如何在Objective-C中将键值对添加到plist文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170871/

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