Is it possible to set up KVO notifications for static variables in objective C?
KVO says that a specific object observes changes on a property of another object (or itself). So i think what you're trying to achieve is not possible, at least not like this. Or at least you need to go deeper on the KVO mechanism.
You can get all information you need to answer your question from Apple Key-Value Observing Programming Guide
Unlike notifications that use NSNotificationCenter, there is no central object that provides change notification for all observers. Instead, notifications are sent directly to the observing objects when changes are made. NSObject provides this base implementation of key-value observing, and you should rarely need to override these methods.
You can fire KVO, with - willChangeValueForKey:
and - didChangeValueForKey:
. You can read more about this at NSKeyValueObserving Protocol Reference
I suggest that you use a different approach, by creating a manager to manage your cache with and observe the values on that cache, just an example.
CacheManager.h
#import <Foundation/Foundation.h>
@interface CacheManager : NSObject
@property (nonatomic, strong, readonly) NSArray *data;
+ (instancetype)sharedManager;
@end
CacheManager.m
#import "CacheManager.h"
@implementation CacheManager
- (instancetype)init {
if (self = [super init]) {
_data = [[NSArray alloc] init];
}
return self;
}
+ (instancetype)sharedManager {
static CacheManager *selfManager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
selfManager = [[[self class] alloc] init];
});
return selfManager;
}
@end
ViewController.m
#import "ViewController.h"
#import "CacheManager.h"
static void *CacheManagerDataChangedContext = &CacheManagerDataChangedContext;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CacheManager *cacheManager = [CacheManager sharedManager];
[cacheManager addObserver:self forKeyPath:NSStringFromSelector(@selector(data)) options:NSKeyValueObservingOptionNew context:CacheManagerDataChangedContext];
}
- (void)dealloc {
[[CacheManager sharedManager] removeObserver:self forKeyPath:NSStringFromSelector(@selector(data)) context:CacheManagerDataChangedContext];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == CacheManagerDataChangedContext) {
<# your stuff #>
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end
If you observe the data
property of CacheManager from all the other instances, all that instance will get notified when that changes.
Hope that helps ;)