2012-04-14 74 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秒鐘,應用程序將被終止。