2

将我的数据保存到 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];

谢谢

4

1 回答 1

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 秒,则应用程序将被终止。

于 2014-05-04T10:50:01.993 回答