App crash when trying to access a subclass method after the object was initialized ( init ) using the parent initializer

非 Y 不嫁゛ 提交于 2020-01-06 05:35:10

问题


I have a class that subclasses NSMutableArray.

I init it using:

MyClass class = [MyClass arrayWithContentsOfFile:path];

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

-[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,

I am suspecting this happens because arrayWithContentsOfFile:path returns NSArray and not "MyClass" so it can't response to my selector.

Any ideas?


回答1:


NSArray is a class cluster. To create a new subclass within a class cluster, you must implement its primitive methods.

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.

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.

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.



来源:https://stackoverflow.com/questions/255679/app-crash-when-trying-to-access-a-subclass-method-after-the-object-was-initializ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!