developer tip

NSUserDefaults 사전 iOS에서 모든 키 삭제

optionbox 2020. 11. 22. 19:23
반응형

NSUserDefaults 사전 iOS에서 모든 키 삭제


사용자가 앱을 닫을 때 데이터가 손실되지 않도록 NSUserDefaults 사전을 사용하여 최고 점수 등과 같은 기본 정보를 저장합니다. 어쨌든 나는 다음을 사용합니다.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

데이터를 저장합니다. 예를 들어 새로운 최고 점수를 저장하려면 다음을 수행합니다.

[prefs setInteger:1023 forKey:@"highScore"];
[prefs synchronize];  //this is needed in case the app is closed. 

나중에 높은 점수를 검색하려면 다음을 수행합니다.

[prefs integerForKey:@"highScore"];

어쨌든 요점은이 때문에 다른 많은 것들을 저장할 수 있다는 것입니다 NSUserDefaults enable가게로 booleans, integers, objects내가 응용 프로그램을 실행 NSUserDefaults는 주먹 시간처럼 될 정도로 모든 키를 삭제하기 위해 실행해야 할 것입니다 무슨 방법 등?

나는 다음과 같은 것을 찾고 있습니다.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs deleteAllKeysAndObjectsInTheDictionary];

또는 모든 키를 가져 오는 방법이 있고 각 개체를 반복해야하지만 제거하는 방법을 모르겠습니다.

편집하다:

나는 시도했다 :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[NSUserDefaults resetStandardUserDefaults];
[prefs synchronize];

여전히 높은 점수를받을 수 있습니다 ....


NSUserDefaults 문서살펴보면 메소드를 볼 수 있습니다 - (NSDictionary *) dictionaryRepresentation. 표준 사용자 기본값에서이 방법을 사용하면 사용자 기본값의 모든 키 목록을 가져올 수 있습니다. 그런 다음이를 사용하여 사용자 기본값을 지울 수 있습니다.

- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

Alex Nichol의 최고 답변과 같은 결과로이 작업을 수행하는 가장 짧은 방법 :

NSString *appDomain = NSBundle.mainBundle.bundleIdentifier;
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize];

짧막 한 농담:

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:NSBundle.mainBundle.bundleIdentifier];

간단한 솔루션

목표 C :

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

에서 스위프트 3.0 :

if let appDomain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: appDomain)
}

Swift 버전 :

if let bid = NSBundle.mainBundle().bundleIdentifier {
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(bid)
}   

+ (void) resetStandardUserDefaults변경 사항을 유지하지 않고 단순히 메모리 내 사용자 기본 개체를 재설정하여 다음 synchronize호출이 기존 메모리 내 값을 온 디스크 버전으로 덮어 쓰는 대신 온 디스크 복사본에서 읽도록합니다.

키를 반복하는 것이 더 좋지만 실제로이를 수행하는 함수가 있습니다 removePersistentDomainForName:..

// you can usually get the domain via [[NSBundle mainBundle] bundleIdentifier]
[[NSUserDefaults standardUserDefaults]
 removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
// or use a string for any other settings domains you use
//[[NSUserDefaults standardUserDefaults]
// removePersistentDomainForName:@"com.mycompany.myappname"];
[[NSUserDefaults standardUserDefaults] synchronize];

At the end of the synchronize operation, both the disk and memory copies of user defaults will contain none of the values set by your application.


For those of you that want to do this in the test target, use this (as the removePersistentDomain does not work for that case)

Swift 3:

for key in Array(UserDefaults.standard.dictionaryRepresentation().keys) {
     UserDefaults.standard.removeObject(forKey: key)
}

Oneliner in Swift:

Swift 3

NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
NSBundle.mainBundle().bundleIdentifier!)

Swift 4

UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)

For Swift 3:

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)

For Swift 3:

if let bundle = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundle)
}

Swift

 func resetUserDefaults(){

    let userDefaults = NSUserDefaults.standardUserDefaults()
    let dict = userDefaults.dictionaryRepresentation() as NSDictionary

    for key in dict.allKeys {

            userDefaults.removeObjectForKey(key as! String)
    }

    userDefaults.synchronize()

}

Swift
place in your logic

if let appDomain = Bundle.main.bundleIdentifier {
       UserDefaults.standard.removePersistentDomain(forName: appDomain)
     }

Does this method not do that:

+ (void)resetStandardUserDefaults

From the documentation for NSUserDefaults:

resetStandardUserDefaults

Synchronizes any changes made to the shared user defaults object and releases it from memory.

+ (void)resetStandardUserDefaults

Discussion

A subsequent invocation of standardUserDefaults creates a new shared user defaults object with the standard search list.

Based on this, you can do:

[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];

and now the defaults should be reset.


Swift 3 or 4 We can even simplify described snippet into this modern expression:

func clearAll() {
    let settingsDictionary = userDefaults.dictionaryRepresentation()
    settingsDictionary.forEach { key, _ in userDefaults.removeObject(forKey: key) }
    userDefaults.synchronize()
}

To remove all UserDefault value in swift (Latest syntax)

//remove UserDefaults
  if let identifier = Bundle.main.bundleIdentifier {
      UserDefaults.standard.removePersistentDomain(forName: identifier)
      UserDefaults.standard.synchronize()
  }

참고URL : https://stackoverflow.com/questions/6797096/delete-all-keys-from-a-nsuserdefaults-dictionary-ios

반응형