How can I remove value that was previously registered via [NSUserDefaults registerDefaults:] call

后端 未结 3 1297
暗喜
暗喜 2021-01-05 10:33

I have bunch of preference values registered via [NSUserDefaults registerDefaults:] call on application startup. I need to replace them at some stage with new o

3条回答
  •  离开以前
    2021-01-05 10:48

    To completely replace the registered defaults, you will replace the NSRegistrationDomain domain (which is volatile, by the way).

    To remove individual registered defaults, you get the values in the NSRegistrationDomain, remove the offending key(s), and replace the domain.

    A category on NSUserDefaults might look something like this:

    @implementation NSUserDefaults (UnRegisterDefaults)
    
    - (void)unregisterDefaultForKey:(NSString *)defaultName {
        NSDictionary *registeredDefaults = [[NSUserDefaults standardUserDefaults] volatileDomainForName:NSRegistrationDomain];
        if ([registeredDefaults objectForKey:defaultName] != nil) {
            NSMutableDictionary *mutableCopy = [NSMutableDictionary dictionaryWithDictionary:registeredDefaults];
            [mutableCopy removeObjectForKey:defaultName];
            [self replaceRegisteredDefaults:[mutableCopy copy]];
        }
    }
    
    - (void)replaceRegisteredDefaults:(NSDictionary *)dictionary {
        [[NSUserDefaults standardUserDefaults] setVolatileDomain:dictionary forName:NSRegistrationDomain];
    }
    
    @end
    

    Motivation:

    The reason I need this is because I want to turn on user-agent spoofing (for reasons of 3rd-party compatibility). User-agent spoofing only appears to work when the value is set via registerDefaults:, so set...:forKey: won't stop the user-agent string it. If I want to stop spoofing the user-agent some time later (without restarting the app), I need a way to remove defaults. Further, I don't want to clear the other registered defaults my app users. The above solution appears to accomplish this perfectly.

提交回复
热议问题