Ho il seguente codice che mira a rilevare l'evento di un valore NSUserDefaults che cambia per una chiave particolare.iOS NSUserDefaults Controllo del cambio di valori per una chiave singola
[[NSUserDefaults standardUserDefaults] addObserver:self
forKeyPath:SOME_NSSTRING_VARIABLE
options:NSKeyValueObservingOptionNew
context:NULL];
- (void)observeValueForKeyPath:(NSString *) keyPath ofObject:(id) object change:(NSDictionary *) change context:(void *) context
{NSLog (@"Changed for key %@", keyPath); }
Ma il observValueForKeyPath non viene mai chiamato. Ho anche provato a sostituire SOME_NSSTRING_VARIABLE con una stringa come indicato in Observing value changes to an NSUserDefaults key ma non ha aiutato.
Aggiornamento: Sto cambiando NSUserDefaults da un tabview. Il codice sopra riportato per monitorare le modifiche si trova in una scheda diversa dello stesso tabviewcontroller. Nella scheda in cui posso monitorare i cambiamenti (la scheda in cui esiste codice di cui sopra), se aggiungo una:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// NSLog(@"viewillappear");
NSUserDefaults *FUDefaults = [NSUserDefaults standardUserDefaults];
NSLog(@"The username obtained is: %@", [FUDefaults objectForKey:SOME_NSSTRING_VARIABLE]);
}
il valore NSUserDefaults aggiornato è ottenuto in modo corretto, ma l'observeValueForKeyPath non è mai stato chiamato.
Si prega di inserire il codice in cui si modifica la variabile anche – trapper
Anche io credo che tu abbia '[[NSUserDefaults st andardUserDefaults] addObserver ... 'all'interno di' viewDidLoad'? – trapper
NSUserDefaults * FDefaults = [NSUserDefaults standardUserDefaults]; [FDefaults setObject: userName.text forKey: SOME_NSSTRING_VARIABLE]; [[NSUserDefaults standardUserDefaults] synchronize]; –