当发生这种情况时,我希望所有A实例在下次访问其属性时从缓存中提取新信息,或者换句话说,使其属性内容无效.
到目前为止,每个实例都是手动通知的(使用静态数组来跟踪成员).我不是粉丝.通知中心可能有一个选项,但我宁愿尝试使用KVO.
有没有人设法从iOS上的类变量订阅KVO更改? (换句话说,使用A的静态变量的变化来告诉A实例刷新它们的数据.)
换句话说,我很乐意拥有
static void* context = &context; static myHadHocObject* msignal;
后来在A类代码中
[msignal addobserver:self forKeyPath:@"operation" options:NSkeyvalueObservingOptionNew context:context];
-(void)observeValueForKeyPath:(Nsstring *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ }
我试过使用各种特殊课程,没有运气.好像我错过了什么.
欢迎指点,谢谢!
解决方法
您可以从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.
你可以使用-willChangeValueForKey:和 – didChangeValueForKey:来激活KVO.您可以在NSKeyValueObserving Protocol Reference了解更多相关信息
我建议您使用不同的方法,通过创建管理器来管理缓存并观察缓存上的值,这只是一个例子.
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
如果您从所有其他实例中观察CacheManager的data属性,那么当该更改时,将通知所有该实例.
希望有所帮助;)