2012-04-14 38 views
2

NSUserDefaultsにデータを保存して重複しないようにする最良の方法は何ですか?ここで私は現在viewWillAppearでやっていることです。私は辞書データの個々のエントリを保存しています。私はこれが最善の方法であり、アドバイスが評価されているかどうかわからないだけでなく、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秒以上かかると、アプリケーションが強制終了されます。

関連する問題