简体   繁体   English

我可以在NSArray上使用自定义类方法返回常量吗?

[英]Can I use a custom class method on NSArray to return a constant?

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 . 为此,我定义了自己的类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 . 在实现文件中,我使类成为单例,然后添加了一个类方法arrayOfTeamNames

To access the array, I use [Constants arrayOfTeamNames]. 要访问数组,请使用[Constants arrayOfTeamNames]。

I this acceptable? 我这个可以接受吗?

I was thinking about how NSString and NSArray themselves handle creation via class methods. 我在考虑NSString和NSArray本身如何通过类方法处理创建。 If, for example, I want an empty array, I can use [NSArray array] - so presumably 'array' is a class method on NSArray. 例如,如果我想要一个空数组,则可以使用[NSArray array] -因此'array'可能是NSArray上的一个类方法。

Therefore, instead of my above implementation, should I be using a category to add '+arrayOfTeamStrings' to NSArray, instead of using my own class? 因此,不是我上面的实现,我应该使用类别向NSArray添加'+ arrayOfTeamStrings'而不是使用我自己的类吗?

Or, alternatively, should I create my own subclass of NSArray and add the class method there? 或者,是否应该创建自己的NSArray子类并在其中添加类方法?

In either case, do I need to make the class a singleton myself? 无论哪种情况,我都需要自己使该类成为单身人士吗? Or is this not necessary? 还是没有必要?

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 . 但是,在这种情况下,我真的坚持arrayOfTeamNames中的一部分内容MyConstants The fact that Team Names is an NSArray isn't as important as the fact that it's a constant for your application. 团队名称是NSArray的事实并不像它对于您的应用程序是常量那样重要。

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, eg extern NSArray * const BPAllTeamNames . 如果MyConstants中定义的值非常不同MyConstants相关,或者只有几个,那么我会考虑摆脱MyConstants作为类,而使用类别甚至使用extern NSArray * const BPAllTeamNames ,例如extern NSArray * const BPAllTeamNames

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM