Sunday, November 9, 2014

How to subclass NSMutableDictionary in Objective C

NSMutableDictionary (as well as other collection class) are cluster class, so they are actually abstract class, as a result, you cannot simply inherit your class from NSMutableDictionary and then just call super class' method to relay the request.

The way to do it is through a proxy object, so your derived class just creates a dummy NSMutableDictionary, but the only thing it does is to relay the caller's request to the proxy object, so you can monitor what methods are called on the NSMutableDictionaryobject, and what are the parameters are used.

The following is a sample class derived from NSMutableDictionary

@interface MyMutableDictionary : NSMutableDictionary
@end

@implementation MyMutableDictionary{
 NSMutableDictionary* _proxy;
}

- (void)removeObjectForKey:(id)aKey{
  [_proxy removeObjectForKey:aKey];
}

- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey{
  [_proxy setObject:anObject forKey:aKey];
}

- (id)objectForKey:(id)aKey{
  return [_proxy objectForKey:aKey];
}

- (NSEnumerator *)keyEnumerator{
    return [_proxy keyEnumerator];
}

- (NSUInteger) count{
    return [_proxy count];
}

- (instancetype)init {
    if (self = [super init]) {
        _proxy = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (instancetype)initWithCapacity:(NSUInteger)numItems{
    self = [super init];
    _proxy = [[NSMutableDictionary alloc] initWithCapacity:numItems];
   return self;
}

- (NSMutableDictionary *)initWithContentsOfFile:(NSString *)path{
    self = [self init];
    _proxy = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    _proxy = [[NSMutableDictionary alloc] initWithCoder:aDecoder];
    return self;
}

@end

No comments:

Post a Comment