我正在尝试在我的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只向我展示了最后的数据...我想我在这里覆盖......我不知道为什么会这样!
如何在不覆盖的情况下继续在数组中保存字典?有什么想法吗?
答案 0 :(得分:2)
由于你正在创建一个模型对象,如果你在其中包含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];
答案 1 :(得分:0)
您需要先读入数据,然后将新词典附加到旧词典中。因此,首先读取文件,然后附加新词典,然后保存。
完整代码:
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];
}
答案 2 :(得分:0)
替换:
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];