2013-05-13 53 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]; 
}