ios - 如何停止覆盖数据

标签 ios objective-c cocoa-touch dictionary overwrite

我正在尝试在我的 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];

Source Code

关于ios - 如何停止覆盖数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485157/

相关文章:

ios - 检测应用程序何时从锁定屏幕与 iOS 7 上的其他屏幕激活

ios - 无法在自定义 TableView 单元格中加载图像

ios - Objective-C : several categories on one class

objective-c - ios gtm-oauth 没有键盘

iphone - 检索 TTPhotoViewController 的 UIImage

iphone - 如何通过 NSDate 对象增加一秒

iphone - 如何以编程方式播放默认电话铃声?

ios - 具有自动布局的 UITableView 中的动态单元格高度

ios - 如何在 ios 中使用 SPGooglePlacesAutocomplete

ios - 仅在 UITableViewCell 中禁用 UIScrollView 的垂直滚动