代码之家  ›  专栏  ›  技术社区  ›  Joseph Tura

Objective-C:向NSMutableDictionary添加一个观察者,当计数达到0时,该字典将收到通知

  •  1
  • Joseph Tura  · 技术社区  · 15 年前

    例如,是否可以有一个类别通过调用原始方法来模拟remove方法,同时检查count是否为0?或者有没有更简单的方法。我试过KVO,但没用。。。

    感谢您的帮助。

    约瑟夫

    2 回复  |  直到 15 年前
        1
  •  1
  •   MrO    15 年前

    在使用字典和其他“类簇”对象时,将它们“子类化”的最简单方法是创建一个子类并将其环绕在同一类型的现有对象上:

    @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
    
        2
  •  1
  •   Joseph Tura    15 年前

    我尝试了我的第一个类别,这似乎是有效的:

    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
    

    我不知道这是否是一个优雅的解决方案,但它似乎工作正常。