将数据保存到NSUserDefaults以避免重复条目的最佳方法是什么?这是我现在在viewWillAppear中所做的事情。我正在存储字典数据的各个条目。我不知道这是否是最佳方式,并且建议得到赞赏,以及如何避免重复的信息。
//
// Keep track of photos that have been viewed by storing the photo data in NSUserDefaults.
//
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *recentlyViewed = [[defaults objectForKey:RECENTLY_VIEWED_KEY] mutableCopy];
if (!recentlyViewed) recentlyViewed = [NSMutableArray array];
[recentlyViewed addObject:self.imageDict];
//
// Keep only MAX number of recently viewed photos.
//
while (recentlyViewed.count > RECENTLY_VIEWED_MAX) {
[recentlyViewed removeObjectAtIndex:0];
}
//
// Write the array back to NSUserDefaults and synchronize it.
//
[defaults setObject:recentlyViewed forKey:RECENTLY_VIEWED_KEY];
[defaults synchronize];
由于
答案 0 :(得分:0)
如果您的意思是如何确保不存储重复项,那么最贪婪且最简单的方法(对大量数据而言效率最高)是:
1. Get the current values from NSUserDefault into a NSMutableArray
2. Check in a for loop if any of the values from the NSMutableArray match with the value you are trying to save.
3. If it does, replace the old value with new (or don't do anything)
4. Save the NSMutableArray back to NSUserDefault.
我就是这样做的,但不建议大价值。如果你在主线程上执行它并且需要超过5秒,应用程序将被终止。