问题描述
我有一个继承NSMutableArray的类.
I have a class that subclasses NSMutableArray.
我使用以下方法初始化它:
I init it using:
当我尝试访问任何子类方法时,应用程序因以下错误而崩溃:
When i try to access any of my subclass methods the app crashes with this error:
我怀疑发生这种情况是因为arrayWithContentsOfFile:path返回NSArray而不是"MyClass",因此它无法响应我的选择器.
I am suspecting this happens because arrayWithContentsOfFile:path returns NSArray and not "MyClass" so it can't response to my selector.
有什么想法吗?
推荐答案
NSArray是类集群.要在类集群中创建新的子类,您必须实现其原始方法.
NSArray is a class cluster. To create a new subclass within a class cluster, you must implement its primitive methods.
如果要继承一个数组的行为,通常最好使用has-a关系而不是is-a.也就是说,要编写一个具有NSArray实例变量的类,并简单地将相关消息转发给它.
If what you want is to inherit the behavior of an array, it's usually a better idea to do that with a has-a relationship, rather than an is-a. That is, to write a class that has an NSArray instance variable, and simply forwards the relevant messages to it.
或者,如果要向NSArray添加新行为,则应通过将方法直接添加到类别.
Or, if you want to add new behavior to NSArray, you should do that by adding methods directly to the NSArray class in a category.
本质上,基本上,如果您想为不同的存储机制提供NSArray接口,则基本上只希望子类化,并且对于该作业,无论如何您都需要实现原始方法.
Essentially, you basically only want to subclass if you want to provide an NSArray interface for a different storage mechanism, and for that job you'd need to implement the primitive methods anyway.
这篇关于使用父初始化程序初始化对象(init)后尝试访问子类方法时,应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!