NSDictionary value replacing instead of adding in Plist

前端 未结 3 961
灰色年华
灰色年华 2020-12-20 02:30

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 02:46

    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];
    

    then finally

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

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

提交回复
热议问题