子类化NSMutableDictionary [英] Subclassing NSMutableDictionary

查看:138
本文介绍了子类化NSMutableDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个NSMutableDictionary的子类,它返回nil而不是在字典中没有键时抛出NSUndefinedKeyException。

I am trying to implement a subclass of NSMutableDictionary that returns nil instead of throwing a NSUndefinedKeyException when the key is not present in the Dictionary.

但是当我尝试将对象添加到我的字典中我

However when I try to add objects to my dictionary I get

[NSMutableDictionary setObject:forKey:]: method only defined for abstract class

NilDictionary.h

NilDictionary.h

@interface NilDictionary : NSMutableDictionary {
} 
@end

NilDctionary.m

NilDctionary.m

@implementation NilDictionary
- (id)valueForUndefinedKey:(NSString *)key {
  return nil;
}
@end

我是否真的必须实施所有方法NSMutableDictionary再次出现在我的子类中,或者是否有其他类我应该进行子类化?

Do I really have to implement all the methods from NSMutableDictionary again in my subclass or is there some other class I should be subclassing?

澄清:我原来的问题归结为我不能够正确阅读文档。

Clarification: My original problem came down to me not being able to read the documentation properly.

如果需要子类NSMutableDictionary,请查看正确的答案。如果你想要一个在你的密钥不存在时返回nil的字典,NSMutableDictionary已经这样做了。

If you need to subclass NSMutableDictionary check out the correct answer. If you want a dictionary that returns nil when your key is not present, NSMutableDictionary does that already.

推荐答案

NSMutableDictionary类参考说:

在子类中,您必须覆盖它们的两种基本方法:

In a subclass, you must override both of its primitive methods:

1。 setObject:forKey:

2。 removeObjectForKey:

您还必须覆盖 NSDictionary 类的基本方法。

You must also override the primitive methods of the NSDictionary class.

NSDictionary类参考说:

如果您确实需要子类 NSDictionary ,则需要考虑由类群集表示的内容因此,这些方法是基于概念的几种原始方法:

If you do need to subclass NSDictionary, you need to take into account that is represented by a Class cluster—there are therefore several primitive methods upon which the methods are conceptually based:

1。计数

2。 objectForKey:

3。 keyEnumerator

4。 initWithObjects:forKeys:count:

在子类中,必须覆盖所有这些方法。

In a subclass, you must override all these methods.

NSDictionary的其他方法通过调用一个或多个这些原语来操作。非原始方法提供了一次访问多个条目的便捷方式。

NSDictionary’s other methods operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once.

您似乎需要覆盖所有这六种方法,使您的 NSMutableDictionary 子类完美无缺。

It seems that you need to override all these six methods to make your NSMutableDictionary subclass work perfect.

这篇关于子类化NSMutableDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆