键值 观察外观类上的静态 NSDictionary



我有一个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变化。但是有 2 种解决方法

1)子类NSMutable字典和触发setObject:forKeyremoveObjectForKey上的通知。
2) 包装您的_downloadOperations写入/删除操作并在那里触发通知。

我建议你使用2)变体,因为子类化NSMutableDictionary不是那么容易。

所以 2) 变体将是这样的。
将这 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];
}

在此之后,您需要通过这 2 种方法在该字典中添加和删除对象。您还可以订阅更改

- (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);
}

最新更新