2010-10-13 17 views

risposta

37

È possibile ascoltare per NSUSerDefaultsDidChange-notifiche con questo:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged) name:NSUserDefaultsDidChangeNotification object:nil]; 

Ogni volta che si cambia NSUserDefaults, viene chiamato il numero defaultsChanged.

Non dimenticare di chiamare [[NSNotificationCenter defaultCenter] removeObserver:self]; quando si desidera interrompere l'ascolto di queste notifiche (è necessario farlo anche quando l'oggetto viene deallocato).

+0

ah ok, ha senso. ora la mia prossima domanda è, come posso determinare quali impostazioni sono state cambiate? – Ben

+3

+1. In genere dovresti aggiungereObserver in '-init' (o' -application: didFinishLaunchingWithOptions: 'per il delegato dell'app) e removeObserver in' -dealloc'. È più facile che tenere traccia di quante volte ci si è registrati (se si aggiungeObserver due volte, viene chiamato due volte ogni volta che viene inviata la notifica, IIRC). –

+2

@ Ben Non esiste un modo reale per determinare quali impostazioni sono state modificate, ma se si cerca qualcosa di specifico, provare a memorizzare la vecchia versione quando viene eseguita la notifica, quindi verificarla la volta successiva. – Emil

0

Ascolta cambiare nelle impostazioni

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:NSUserDefaultsDidChangeNotification object:nil]; 

Ricordarsi di rimuovere l'osservatore, una volta che questo controller della vista non è più in memoria.

11

La sintassi è per Swift 2. Utilizzo Swift si dovrebbe fare qualcosa di simile a iscriversi a cambiamenti per le NSUserDefaults:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsChanged:", name: NSUserDefaultsDidChangeNotification, object: nil) 

Quindi creare il metodo come questo:

func defaultsChanged(notification:NSNotification){ 
    if let defaults = notification.object as? NSUserDefaults { 
     //get the value for key here 
    } 
} 
+3

Sintassi per Swift 3: 'NotificationCenter.default.addObserver (self, selector: #selector (self.defaultsChanged), nome: UserDefaults.didChangeNotification, object: nil) ' –

2

Un esempio accesso a un'impostazione di tipo Bool specifica dell'app con chiave "instantWeb":

func observeUserDefaults(notification: NSNotification) { 
    print("Settings changed") 
    if let defaults = notification.object as? NSUserDefaults { 
     if defaults.valueForKey("instantWeb") as! Bool==true { 
      print("Instant Web ON") 
     } 
    } 
} 
-1

In iOS10, prova questo:

UNUserNotificationCenter.current().getNotificationSettings { (settings) in 
    // Your code here 
} 
Problemi correlati