我假设你有一个类似于这个的结构
[
{
"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];
}
在已保存的笔记中插入一条笔记
- (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];
}