Skip to content

Instantly share code, notes, and snippets.

@phatblat
Last active May 14, 2020 08:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phatblat/f640416c15e11b685511 to your computer and use it in GitHub Desktop.
Save phatblat/f640416c15e11b685511 to your computer and use it in GitHub Desktop.
Repost NSUserDefaultsDidChangeNotification to iOS extensions
#pragma mark - App Singleton
- (instancetype)init {
...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:nil];
...
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
CFNotificationCenterRef const center = CFNotificationCenterGetDarwinNotifyCenter();
CFNotificationCenterPostNotification(center, (__bridge CFStringRef)@"defaultsChangedOnTheOtherSide", NULL, NULL, YES);
}
#pragma mark - Extension Observers
- (instancetype)init {
...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:) name:@"localDefaultsChangedNotification" object:nil];
...
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
// Do stuff
}
#pragma mark - Extension Singleton
- (instancetype)init {
...
[self registerForDarwinNotifications];
...
}
- (void)dealloc {
[self unregisterForDarwinNotifications];
}
- (void)registerForDarwinNotifications {
CFNotificationCenterRef const center = CFNotificationCenterGetDarwinNotifyCenter();
CFStringRef str = (__bridge CFStringRef)@"defaultsChangedOnTheOtherSide";
CFNotificationCenterAddObserver(center,
(__bridge const void *)(self),
notificationCallback,
str,
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
}
- (void)unregisterForDarwinNotifications {
CFNotificationCenterRef const center = CFNotificationCenterGetDarwinNotifyCenter();
CFStringRef str = (__bridge CFStringRef)@"defaultsChangedOnTheOtherSide";
CFNotificationCenterRemoveObserver(center,
(__bridge const void *)(self),
str,
NULL);
}
void notificationCallback(CFNotificationCenterRef center,
void * observer,
CFStringRef name,
void const * object,
CFDictionaryRef userInfo) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"localDefaultsChangedNotification"
object:nil
userInfo:nil];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment