これに似た構造を持っていると思います
[
{
"UserID": 1,
"Notes": [
{
"NoteID": 1,
"Desc": "Description"
},{
"NoteID": 2,
"Desc": "Description"
}
]
}
]
ドキュメント ディレクトリの Plist ファイル パス
- (NSString *)userNotesFilePath{
NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)[0];
return [documents stringByAppendingPathComponent:@"UserNotes.plist"];
}
ユーザー ID の保存済みメモを取得するメソッド
- (NSArray *)savedNotesForUserID:(NSInteger)userID{
NSString *filePath = [self userNotesFilePath];
NSArray *savedNotes = [NSArray arrayWithContentsOfFile:filePath];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UserID = %d",userID];
NSDictionary *user = [[savedNotes filteredArrayUsingPredicate:predicate]lastObject];
return user[@"Notes"];
}
新しいメモ配列をそのまま特定のユーザー ID に保存します
- (void)insertNotes:(NSArray *)notesArray forUserID:(NSUInteger)userID{
if (!notesArray) {
return;
}
NSString *filePath = [self userNotesFilePath];
NSMutableArray *savedNotes = [NSMutableArray arrayWithContentsOfFile:filePath];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UserID = %d",userID];
NSInteger index = [savedNotes indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
return [predicate evaluateWithObject:obj];
}];
NSMutableDictionary *user = [savedNotes[index] mutableCopy];
user[@"Notes"] = notesArray;
[savedNotes replaceObjectAtIndex:index withObject:user];
[savedNotes writeToFile:filePath atomically:YES];
}
保存したメモに 1 つのメモを挿入する
- (void)insertNote:(NSDictionary *)userNote forUserID:(NSUInteger)userID{
if (!userNote) {
return;
}
NSString *filePath = [self userNotesFilePath];
NSMutableArray *savedNotes = [NSMutableArray arrayWithContentsOfFile:filePath];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UserID = %d",userID];
NSInteger index = [savedNotes indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
return [predicate evaluateWithObject:obj];
}];
NSMutableDictionary *user = [savedNotes[index] mutableCopy];
NSMutableArray *savedUserNotes = [user[@"Notes"] mutableCopy];
if (!savedUserNotes) {
savedUserNotes = [NSMutableArray array];
}
[savedUserNotes addObject:userNote];
user[@"Notes"] = savedUserNotes;
[savedNotes replaceObjectAtIndex:index withObject:user];
[savedNotes writeToFile:filePath atomically:YES];
}