0

我设法成功地将数据保存到 plist(在本例中为书签列表),但我似乎无法弄清楚如何防止用户两次保存相同的数据。我正在使用“moveRowAtIndexPath”重新排序书签。当列表中有重复项时,会在排序过程中导致崩溃。这是我的代码:

- (IBAction)addBookmarkButtonClicked:(id)sender {

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Bookmarks.plist"];
NSMutableArray *bookmarksArray = [NSMutableArray arrayWithContentsOfFile:plistPath];

if (nil == bookmarksArray) {
    bookmarksArray = [[NSMutableArray alloc] initWithCapacity:0];
}

NSMutableDictionary *array = [[NSMutableDictionary alloc]init];

[array setObject:gameName.text.self forKey:@"gameName"];
[array setObject:gameRating.text.self forKey:@"gameRating"];

[bookmarksArray addObject:array];
[bookmarksArray writeToFile:plistPath atomically: TRUE];

}
4

1 回答 1

0

在将项目添加到 BookmarksArray 之前,您应该检查它是否已经存在。您可以通过遍历 BookmarksArray 中的所有项目并将每个项目的键与您尝试添加的新值进行比较来做到这一点。例子:

BOOL itemExist, sameName, sameRating;
itemExist=NO;
sameName=NO;
sameRating=NO;

For (int i=0, i<[bookmarksArray count], i++) {
    If ([gameName.text isEqualToString:[[bookmarksArray itemAtIndex:i] itemForKey:gameName]]) {
        sameName=YES;
    }
    If ([gameRating.text isEqualToString:[[bookmarksArray itemAtIndex:i] itemForKey:gameRating]]) {
        sameRating=YES;
    }
    if (sameName && sameRating) itemExist=YES;
    sameName=NO;
    sameRating=NO;
}

if (!itemExist) { 
   //item can be added
}
于 2012-10-22T02:10:19.857 回答