I am trying to subclass NSArray
, but it crashes the app when trying to access the count method. I know that NSArray
is a class cluster.
I know that I can simply subclass NSObject
and have my array as an instance variable but I would rather subclass NSArray
.
EDIT:
Reason:
I am creating a card game, I have a class Deck
which should subclass NSMutableArray
to have a couple of extra methods (-shuffle
, -removeObjects:
, -renew
, etc), and I think it will look cleaner to subclass NSArray
rather than having a var.
The problem with adding a category on a class like this is that all instances of the class will inherit the additional methods. That's both unnecessary (since not every array needs to be able to be shuffled, etc.) and dangerous (because you can't benefit from typechecking to be sure the NSArray you're currently referring to is really one that was expected to be shuffled).
An alternative would be to create your own Deck class that has an NSMutableArray as an instance variable. There you can define actions on your deck exactly as you would like, and the fact that you are using an NSMutableArray becomes an implementation detail. This lets you take advantage of typechecking at compile-time and it lets you change the internal implementation of your Deck class without changing its clients. For instance, if you decided for some reason that an NSMutableDictionary would be a better backing store, you can make all those changes within the implementation of your Deck class without changing any of the code that creates and uses the Deck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With