2

我正在尝试在我的 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 只显示了最后的数据......我想我在这里覆盖......我不明白为什么!

我怎样才能继续在数组中保存字典而不覆盖?有任何想法吗?

4

3 回答 3

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];

源代码

于 2013-05-10T16:51:17.147 回答
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];
}
于 2013-05-10T14:58:55.323 回答
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];
于 2013-05-10T14:59:10.113 回答