的NSDictionary:方法只用于抽象类定义。 我的应用程序崩溃(NSDictionary:

2019-06-24 22:16发布

我的应用程序崩溃我叫addImageToQueue后。 我加initWithObjects:forKeys:数:但它不会帮我。

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '*** -[NSDictionary initWithObjects:forKeys:count:]: 
method only defined for abstract class.  
Define -[DictionaryWithTag initWithObjects:forKeys:count:]!'

我的代码

- (void)addImageToQueue:(NSDictionary *)dict
{
 DictionaryWithTag *dictTag = [DictionaryWithTag dictionaryWithDictionary:dict];
}

@interface DictionaryWithTag : NSDictionary
@property (nonatomic, assign) int tag;

- (id)initWithObjects:(id *)objects forKeys:(id *)keys count:(NSUInteger)count;

@end

@implementation DictionaryWithTag

@synthesize tag;

- (id)initWithObjects:(id *)objects forKeys:(id *)keys count:(NSUInteger)count
{
 return [super initWithObjects:objects forKeys:keys count:count];
}
@end

Answer 1:

你继承的NSDictionary? 这不是在可可的土地做一个平常的事,这或许可以解释为什么你没有看到您所期望的结果。

的NSDictionary是一类集群。 这意味着,你从来没有真正用的NSDictionary的实例工作,而是用其私人的一个子类。 见苹果的一类集群的描述在这里 。 从文档:

您创建和使用,就像对其他任何类集群的实例进行交互。 在幕后,但是,当您创建公共类的实例,该类返回根据您调用的创建方法适当的子类的对象。 (你不这样做,而不能选择实际的类实例的。)

你的错误信息,告诉你的是,如果你想继承NSDictionary中,你必须(在写C哈希表为例)来实现它自己的后端存储。 这不只是要求你声明的方法,它要求你从头开始写,处理自己的存储。 这是因为继承类簇一样,直接就是等于说你要为字典是如何工作的一个新的实现。 正如我敢肯定,你可以看出,这是一个显著的任务。

假设你一定要继承的NSDictionary,最好的办法是写你的子类包含一个正常的NSMutableDictionary作为属性,并用它来处理您的存储。 本教程向您展示这样做的方法之一。 这实际上并没有那么难,你只需要通过传递所需的方法,以你的字典财产。

你也可以尝试使用关联引用 ,其中“模拟加法对象的实例变量的向现有类”。 你可以一个NSNumber与您现有的字典相关联这样的话来表示标签,而无需子类。

当然,你也可以只是tag在词典中的一个关键,并存储在它里面的价值像任何其他辞典键。



Answer 2:

从https://stackoverflow.com/a/1191351/467588 ,这是我做的,使一个子类的NSDictionary工作。 我只需要声明一个NSDictionary作为我的类的实例变量,并添加一些必要的方法。 这就是所谓的“组合对象” -感谢@mahboudz。

@interface MyCustomNSDictionary : NSDictionary {
    NSDictionary *_dict;
}
@end

@implementation MyCustomNSDictionary
- (id)initWithObjects:(const id [])objects forKeys:(const id [])keys count:(NSUInteger)cnt {
    _dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:cnt];
    return self;
}
- (NSUInteger)count {
    return [_dict count];
}
- (id)objectForKey:(id)aKey {
    return [_dict objectForKey:aKey];
}
- (NSEnumerator *)keyEnumerator {
    return [_dict keyEnumerator];
}
@end


Answer 3:

我只是做了一个小窍门。
我不知道它的最佳解决方案(甚至它是很好的做到这一点)。

@interface MyDictionary : NSDictionary

@end  

@implementation MyDictionary

+ (id) allocMyDictionary
{
    return [[self alloc] init];
}

- (id) init
{
    self = (MyDictionary *)[[NSDictionary alloc] init];

    return self;
}

@end

这对我来说工作得很好。



文章来源: NSDictionary: method only defined for abstract class. My app crashed