使用父初始化程序初始化对象(init)后尝试访问子类方法时,应用程序崩溃 [英] App crash when trying to access a subclass method after the object was initialized ( init ) using the parent initializer

查看:79
本文介绍了使用父初始化程序初始化对象(init)后尝试访问子类方法时,应用程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承NSMutableArray的类.

I have a class that subclasses NSMutableArray.

我使用以下方法初始化它:

I init it using:

MyClass class = [MyClass arrayWithContentsOfFile:path];

MyClass class = [MyClass arrayWithContentsOfFile:path];

当我尝试访问任何子类方法时,应用程序因以下错误而崩溃:

When i try to access any of my subclass methods the app crashes with this error:

-[NSCFArray loadCards]:无法识别的选择器已发送到实例0x454a30 *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* -[NSCFArray> mymethod]:无法识别的选择器已发送到实例0x454a30' app [32259:20b]堆栈:( 2524995915,

-[NSCFArray loadCards]: unrecognized selector sent to instance 0x454a30 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFArray > mymethod]: unrecognized selector sent to instance 0x454a30' app[32259:20b] Stack: ( 2524995915,

我怀疑发生这种情况是因为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)后尝试访问子类方法时,应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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