如何停止覆盖数据
我想在我的iOS应用程序中保存一些数据。 我使用以下代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourPlist.plist"]; //inserting data NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setValue:categoryField.text forKey:@"Category"]; [dict setValue:nameField.text forKey:@"Name"]; [dict setValue:eventField.text forKey:@"Event"]; NSMutableArray *arr = [[NSMutableArray alloc] init]; [arr addObject:dict]; [arr writeToFile: path atomically:YES]; //retrieving data NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile: path]; for (NSDictionary *dict in savedStock) { NSLog(@"my Note : %@",dict); }
然而NSLog只向我展示了最后的数据……我想我在这里覆盖……我不知道为什么会这样!
如何在不覆盖的情况下继续在数组中保存字典? 有任何想法吗?
由于你正在制作一个模型对象,如果你在其中包含save,remove,findAll,findByUniqueId类型的逻辑会更好。 将使模型对象的使用变得非常简单。
@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;
保存一个便条
Note *note = [Note new]; note.category = ... note.name = ... note.event = ... [note save];
从保存的列表中删除
//Find the reference to the note you want to delete Note *note = self.savedNotes[index]; [note remove];
查找所有保存的笔记
NSArray *savedNotes = [Note savedNotes];
源代码
更换:
NSMutableArray *arr = [[NSMutableArray alloc] init]; [arr addObject:dict]; [arr writeToFile: path atomically:YES];
附:
NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile: path]; [arr addObject:dict]; [arr writeToFile: path atomically:YES];
您需要先读入数据,然后将新词典附加到旧词典。 因此,首先读取文件,然后附加新字典,然后保存。
完整代码:
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]; }