我尝试了我的第一个类别,这似乎是有效的:
NSMutableDictionary+notificationsonempty.h
#import <Foundation/Foundation.h>
@interface NSMutableDictionary (NotifiesOnEmpty)
- (void)removeObjectForKeyNotify:(id)aKey;
- (void)removeAllObjectsNotify;
- (void)removeObjectsForKeysNotify:(NSArray *)keyArray;
- (void)notifyOnEmpty;
@end
#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
我不知道这是否是一个优雅的解决方案,但它似乎工作正常。