NSDictionary值替换而不是在Plist中添加 [英] NSDictionary value replacing instead of adding in Plist

查看:63
本文介绍了NSDictionary值替换而不是在Plist中添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我尝试将NSdictionary中的值(书ID,页号,注释)添加到Plist,但是每次新值替换上一个值时,但我需要plist中的所有值,我将字典添加到plist的代码是

hi i tried to add values(book id,page number,notes) from NSdictionary to Plist but each time the new value replacing the previous one?but i need all values in plist my code for adding dictionary to plist is

NSString *bid=@"95";
NSString *pnum=@"12";
userNotes=[[NSMutableDictionary alloc]init];
[userNotes setValue:userNotesTextview.text forKey:@"notes"];
[userNotes setValue:bid forKey:@"bookid"];
[userNotes setValue:pnum forKey:@"pagenumber"];
userNotesView.hidden=YES;
_background.hidden = YES;
userNotesTextview.text=@"";
[self savingMetaData];
  NSMutableArray *notes=[[NSMutableArray alloc]init];
  [notes addObject:userNotes];

  NSMutableDictionary *final=[[NSMutableDictionary alloc]init];
  [final setValue:notes forKey:@"usernotes"];
  [final writeToFile:metaDataPath atomically:YES];

我的plist看起来像

and my plist look like

我该如何解决这个问题

推荐答案

从plist中获取现有数组,如下所示,但首先请确保已将plist复制到Documents目录或以下某个可写文件夹中

Fetch the existing array from the plist as below, but first make sure you have copied you plist to Documents directory or, to some writable folder as below

NSFileManager *fileManager=[NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *docPath=[[paths objectAtIndex:0] stringByAppendingString:@"yourplist.plist"];
BOOL fileExists = [fileManager fileExistsAtPath: docPath];
NSError *error = nil;
if(!fileExists) 
{
    NSString *strSourcePath = [[NSBundle mainBundle] pathForResource:@"yourplist" ofType:@"plist"];

    [fileManager copyItemAtPath:strSourcePath toPath:docPath error:&error];         

}

NSString *path = docPath;
NSMutableDictionary *plistdictionary = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
NSMutableArray *notes=[plistdictionary objectForKey:@"usernotes"];
if(notes==nil){ 
   notes=[[NSMutableArray alloc] init]; 
}
NSString *bid=@"95";
NSString *pnum=@"12";
userNotes=[[NSMutableDictionary alloc]init];
[userNotes setValue:userNotesTextview.text forKey:@"notes"];
[userNotes setValue:bid forKey:@"bookid"];
[userNotes setValue:pnum forKey:@"pagenumber"];
[notes addObject:userNotes];

然后终于

NSMutableDictionary *final=[[NSMutableDictionary alloc]init];
[final setValue:notes forKey:@"usernotes"];
[final writeToFile:docPath atomically:YES];

注意:您不能在MainBundle中编写任何内容,因此最好将plist复制到Documents目录并从那里使用.

Note: You cannot write anything in MainBundle, so better to copy your plist to Documents directory and use from there..

这篇关于NSDictionary值替换而不是在Plist中添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆