2013-05-13 51 views
-2

我有一个plist,当一个用户写下笔记时,我将它们和他们的id一起保存到plist中,每次用户打开时它都会检查这个用户id是否在plist中有任何笔记并将其显示在uitableview中。用户也可以删除笔记,但是当我试着做下面的过程中,我得到异常从Plist中删除不起作用?

1.in视图didload检查用户是否有任何以前的笔记或不使用用户ID 3.如果匹配 2.检查plist中获取相应说明 4并将其保存到一个可变数组.so当用户首先添加一个新的音符时,我们使用先前的可变数组来存储新的音符并将其重新写入plist //不为我工作。 5.当用户删除然后笔记itinto的plist

+1

曾经认为,在编码的网站,显示会比所述代码的描述更好的代码? – 2013-05-13 04:47:55

回答

1

更新我假设你有类似的文件目录这个

[ 
    { 
     "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]; 
}