0

I frequently need to refer to an array of strings (let's say team names) in multiple places. The contents of that array to not change.

To achieve this, I defined my own class, MyConstants. In the header I am defining some unrelated constant strings and numbers. In the implementation file, I made the class a singleton, and then added a class method arrayOfTeamNames.

To access the array, I use [Constants arrayOfTeamNames].

I this acceptable?

I was thinking about how NSString and NSArray themselves handle creation via class methods. If, for example, I want an empty array, I can use [NSArray array] - so presumably 'array' is a class method on NSArray.

Therefore, instead of my above implementation, should I be using a category to add '+arrayOfTeamStrings' to NSArray, instead of using my own class?

Or, alternatively, should I create my own subclass of NSArray and add the class method there?

In either case, do I need to make the class a singleton myself? Or is this not necessary?

Ben Packard
  • 26,102
  • 25
  • 102
  • 183
  • 2
    Seems like your over thinking it and if you keep worrying about it you might have a stress attack. What you have seems fine and if you are really worried about something else changing your already immutable array setup sometime of property setter type method. – rezand Jul 23 '13 at 13:59

1 Answers1

0

In general, there can be very good uses for adding class methods to foundation classes via categories. But in this case, I would actually stick with arrayOfTeamNames being part of MyConstants. The fact that Team Names is an NSArray isn't as important as the fact that it's a constant for your application.

If the values defined in MyConstants are very diverse and unrelated, or if there are only a couple of them, then I would consider just getting rid of MyConstants as a class and using categories or even just externs, e.g. extern NSArray * const BPAllTeamNames.

Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75