保存到Plist时防止重复

时间:2012-10-21 23:44:44

标签: iphone objective-c ios

我设法成功地将数据保存到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];

}

1 个答案:

答案 0 :(得分: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
}