[英]How to add a key-value pair to a plist file in Objective-C
我正在開發一個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
文件復制到文檔目錄中並在那里進行操作。
這些方面的東西:
//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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.