2012-04-14 91 views
2

将数据保存到NSUserDefaults以避免重复条目的最佳方法是什么?这是我现在正在做的事情。我正在存储单个词条数据的条目。我不知道这是否是最好的方式和建议,以及有关如何避免dups的信息。存储NSUserDefaults时避免重复(Xcode)

// 
// 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

如果你的意思是如何确保副本不被存储,这样做(不是最有效的大量数据)的最贪婪而简便的方法是:

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