Objective C: Добавьте наблюдателя к NSMutableDictionary, который уведомляется, когда количество достигает 0

Я хотел бы быть уведомленным, когда количество NSMutableDictionary достигает 0. Это возможно, не расширяя NSMutableDictionary (который я слышал, что Вы не должны действительно делать)?

Мог я, например, иметь категорию, которая имитирует, удаляют методы путем вызова исходных при проверке, является ли количество 0? Или есть ли, возможно, более простой путь. Я попробовал KVO, но это не работало...

Любая справка ценится.

Joseph

1
задан Joseph Tura 30 July 2010 в 11:07
поделиться

2 ответа

При работе со словарями и другими объектами «кластера классов» самый простой способ «создать подкласс» - создать подкласс и обернуть его вокруг существующего объекта. того же типа:

@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
1
ответ дан 2 September 2019 в 22:34
поделиться

Я попробовал свою первую категорию, которая, кажется, работает:

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

Не знаю, элегантное ли это решение, но кажется, работать нормально.

1
ответ дан 2 September 2019 в 22:34
поделиться