Ios facade类上的键值
我有一个Ios facade类上的键值,ios,objective-c,observer-pattern,nsmutabledictionary,key-value-observing,Ios,Objective C,Observer Pattern,Nsmutabledictionary,Key Value Observing,我有一个ServiceFacade类,其中包含用于与后端服务通信的类方法。 在ServiceFacade类上,我有一个静态方法,返回NSMutableDictionary,其中我保持当前ServiceFacade的下载操作。 我想在AppDelegate或任何其他位置观察此NSMutableDictionary上的更改。应用程序代理似乎没有响应 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPa
ServiceFacade
类,其中包含用于与后端服务通信的类方法。
在ServiceFacade
类上,我有一个静态方法,返回NSMutableDictionary
,其中我保持当前ServiceFacade
的下载操作。
我想在AppDelegate
或任何其他位置观察此NSMutableDictionary
上的更改。应用程序代理似乎没有响应
- (void)addObserver:(NSObject *)anObserver
forKeyPath:(NSString *)keyPath
options:(NSKeyValueObservingOptions)options
context:(void *)context{
}
返回NSMutableDictionary的方法:
+(NSMutableDictionary *)downloadOperations
{
if (_downloadOperations)
{
return _downloadOperations;
}
[_downloadOperations addObserver:[AppDelegate sharedAppDelegate] forKeyPath:@"downloadOperationsDict" options:0 context:NULL];
_downloadOperations = [NSMutableDictionary dictionary];
return _downloadOperations;
}
有什么想法吗?没有办法观察
NSMutableDictionary
的变化。但有两个变通办法
1) 子类NSMutableDictionary和setObject:forKey
和removeObjectForKey
上的触发器通知2) 将您的_downloadOperations写入/删除操作和触发通知包装在此处 我建议您使用variant,因为子类化
NSMutableDictionary
并不容易
所以2)变体将是这样的。将这两个方法添加到类
ServiceFacade
- (void)setDownloadObject:(id)aObj forKey:(id<NSCopying>)aKey
{
[self.downloadOperations setObject:aObj forKey:aKey];
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadOperationsChanged" object:self
userInfo:self.downloadOperations];
}
- (id)removeDownloadObjectForKey:(id<NSCopying>)aKey
{
[[self.downloadOperations] removeObjectForKey:aKey];
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadOperationsChanged" object:self
userInfo:self.downloadOperations];
}
仅当
\u downloadOperations
指针发生变化时才会触发KVO。变异\u downloadOperations
所指向的字典内容不会触发KVO通知。不,只有在执行-setDownloadOperation
时才会触发。这就是问题所在,是的。对不起,这是我的意思,但解释得很糟糕。这是我的备份解决方案。谢谢你的邀请!
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(downloadOperationsChanged:)
name:@"DownloadOperationsChanged"
object:nil];
return YES;
}
- (void)downloadOperationsChanged:(NSNotification *)aNotification
{
NSLog(@"Operations : %@", aNotification);
}