Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Subclassing NSArray

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.

  • But what does this mean?
  • Is there a work around to be able to subclass an NSArray?

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.

like image 452
aryaxt Avatar asked Dec 04 '10 01:12

aryaxt


1 Answers

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.

like image 129
Ryan Avatar answered Oct 07 '22 11:10

Ryan