1

NSMutableDictionary のカウントが 0 に達したときに通知を受け取りたいのですが、それは NSMutableDictionary を拡張せずに可能ですか (実際にはすべきではないと聞きました)?

たとえば、count が 0 かどうかをチェックしながら元のメソッドを呼び出して、remove メソッドを模倣するカテゴリを作成できますか? それとも、もっと簡単な方法がありますか。KVOを試してみましたが、うまくいきませんでした...

どんな助けでも大歓迎です。

ジョセフ

4

2 に答える 2

1

辞書やその他の「クラス クラスター」オブジェクトを操作する場合、それらを「サブクラス化」する最も簡単な方法は、サブクラスを作成し、同じ型の既存のオブジェクトをラップすることです。

@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
于 2010-07-30T15:10:47.577 に答える
1

私は初めてのカテゴリで試してみましたが、うまくいくようです:

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

それがエレガントな解決策かどうかはわかりませんが、うまくいくようです。

于 2010-07-30T11:44:11.637 に答える