我正在尝试在我的 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];
源代码 https://dl.dropboxusercontent.com/u/35012982/Demo%20Projects/TestPlistWriter_V2.1.zip
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)