简体   繁体   English

objective-c中的常量类

[英]Constant class in objective-c

I have read some posts about constants in Objective-C and I have concluded that is better to create a header and a implementation. 我已经在Objective-C阅读了一些关于常量的帖子,我得出结论,最好创建一个头和一个实现。

The problem is this. 问题是这个。 What class should I extend? 我应该扩展什么课程? NSDocument ? NSDocument Xcode does not allow me to create a class without a subclass. Xcode不允许我创建没有子类的类。

I guess you mean a place to declare some global constants. 我想你的意思是一个声明一些全局常量的地方。 If that's the case, then you don't really to define a class. 如果是这种情况,那么你真的没有定义一个类。

To be more specific, if your constants are only primitive data and strings. 更具体地说,如果你的常量只是原始数据和字符串。 You can define them in a .h file and declare them in a .m file. 您可以在.h文件中定义它们并在.m文件中声明它们。

Constants.h Constants.h

extern NSString *const ConstString;
extern const NSInteger ConstInt;

Constants.m Constants.m

NSString *const ConstString = @"asdasd";
const NSInteger ConstInt = 12;

However, if you need to define constant custom objects. 但是,如果需要定义常量自定义对象。 Then you may need a custom singleton class for that. 那么你可能需要一个自定义单例类。 You can reach constants through the singleton's methods. 你可以通过单例的方法达到常数。 The singelton class should be a subclass of NSObject , because, as @Peter Pei Guo said, that's the base class for all Objective-C classes. singelton类应该是NSObject的子类,因为正如@Peter Pei Guo所说,这是所有Objective-C类的基类。

I would say simply extend NSObject . 我会说只是扩展NSObject

I do not feel that NSDocument fits the purpose here, since it already has its particular purpose and not related to what you are doing here. 我并不觉得NSDocument符合这里的目的,因为它已经有了它的特殊目的,与你在这里所做的事情无关。 According to the document of NSDocument : 根据NSDocument的文件:

The NSDocument abstract class defines the interface for OS X documents. NSDocument抽象类定义OS X文档的接口。 A document is an object that can internally represent data displayed in a window and that can read data from and write data to a file or file package. 文档是一个对象,可以在内部表示窗口中显示的数据,并且可以从文件或文件包中读取数据并将数据写入文件或文件包。

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

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