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 に答える