我想在 NSMutableDictionary 的计数达到 0 时收到通知。如果不扩展 NSMutableDictionary(我听说你不应该这样做),这是否可能?
例如,我是否可以通过在检查计数是否为 0 时调用原始方法来模仿删除方法?或者有没有更简单的方法。我尝试了KVO,但没有奏效......
任何帮助表示赞赏。
约瑟夫
我想在 NSMutableDictionary 的计数达到 0 时收到通知。如果不扩展 NSMutableDictionary(我听说你不应该这样做),这是否可能?
例如,我是否可以通过在检查计数是否为 0 时调用原始方法来模仿删除方法?或者有没有更简单的方法。我尝试了KVO,但没有奏效......
任何帮助表示赞赏。
约瑟夫
我尝试了我的第一个类别,这似乎有效:
NSMutableDictionary+NotifiesOnEmpty.h
#import <Foundation/Foundation.h>
@interface NSMutableDictionary (NotifiesOnEmpty)
- (void)removeObjectForKeyNotify:(id)aKey;
- (void)removeAllObjectsNotify;
- (void)removeObjectsForKeysNotify:(NSArray *)keyArray;
- (void)notifyOnEmpty;
@end
NSMutableDictionary+NotifiesOnEmpty.m
#import "Constants.h"
#import "NSMutableDictionary+NotifiesOnEmpty.h"
@implementation NSMutableDictionary (NotifiesOnEmpty)
- (void)removeObjectForKeyNotify:(id)aKey {
[self removeObjectForKey:aKey];
[self notifyOnEmpty];
}
- (void)removeAllObjectsNotify {
[self removeAllObjects];
[self notifyOnEmpty];
}
- (void)removeObjectsForKeysNotify:(NSArray *)keyArray {
[self removeObjectsForKeys:keyArray];
[self notifyOnEmpty];
}
- (void)notifyOnEmpty {
if ([self count] == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationDictionaryEmpty object:self];
}
}
@end
不知道这是否是一个优雅的解决方案,但它似乎工作正常。
使用字典和其他“类集群”对象时,“子类化”它们的最简单方法是创建一个子类并将其包装在相同类型的现有对象周围:
@interface MyNotifyingMutableDictionary:NSMutableDictionary {
NSMutableDictionary *dict;
}
// these are the primitive methods you need to override
// they're the ones found in the NSDictionary and NSMutableDictionary
// class declarations themselves, rather than the categories in the .h.
- (NSUInteger)count;
- (id)objectForKey:(id)aKey;
- (NSEnumerator *)keyEnumerator;
- (void)removeObjectForKey:(id)aKey;
- (void)setObject:(id)anObject forKey:(id)aKey;
@end
@implementation MyNotifyingMutableDictionary
- (id)init {
if ((self = [super init])) {
dict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (NSUInteger)count {
return [dict count];
}
- (id)objectForKey:(id)aKey {
return [dict objectForKey:aKey];
}
- (NSEnumerator *)keyEnumerator {
return [dict keyEnumerator];
}
- (void)removeObjectForKey:(id)aKey {
[dict removeObjectForKey:aKey];
[self notifyIfEmpty]; // you provide this method
}
- (void)setObject:(id)anObject forKey:(id)aKey {
[dict setObject:anObject forKey:aKey];
}
- (void)dealloc {
[dict release];
[super dealloc];
}
@end