How to stop overwriting data

对着背影说爱祢 提交于 2019-12-06 13:23:44

Since you are making a model object it would be better if you include save, remove, findAll, findByUniqueId kind of logic built into it. Will make working with the model object very simple.

@interface Note : NSObject

@property (nonatomic, copy) NSString *category;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *event;

- (id)initWithDictionary:(NSDictionary *)dictionary;

/*Find all saved notes*/
+ (NSArray *)savedNotes;

/*Saved current note*/
- (void)save;

/*Removes note from plist*/
- (void)remove;

Save a note

Note *note = [Note new];
note.category = ...
note.name = ...
note.event = ...

[note save];

Delete from saved list

//Find the reference to the note you want to delete
Note *note = self.savedNotes[index];
[note remove];

Find all saved notes

NSArray *savedNotes = [Note savedNotes];

Source Code

Replace:

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:dict];
[arr writeToFile: path atomically:YES];

With:

NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile: path];
[arr addObject:dict];
[arr writeToFile: path atomically:YES];

You need to first read in the data, then APPEND the new dictionary to the old one. So read the file first, then append the new dictionary, then save.

FULL CODE:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:categoryField.text forKey:@"Category"];
[dict setValue:nameField.text forKey:@"Name"];
[dict setValue:eventField.text forKey:@"Event"];

[self writeDictionary:dict];

- (void)writeDictionary:(NSDictionary *)dict
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourPlist.plist"];

    NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile: path];
    if(!savedStock) {
        savedStock = [[[NSMutableArray alloc] initiWithCapacity:1];
    }
    [savedStock addObject:dict];

    // see what';s there now
    for (NSDictionary *dict in savedStock) {
         NSLog(@"my Note : %@",dict);
    }
    // now save out
    [savedStock writeToFile:path atomically:YES];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!