Cocoa/Cocoa Touch中的许多类都有NS前缀。这是什么意思?
当前回答
苹果的开发者文档如下:
Historical Note: If you’re wondering why so many of the classes you encounter have an NS prefix, it’s because of the past history of Cocoa and Cocoa Touch. Cocoa began life as the collected frameworks used to build apps for the NeXTStep operating system. When Apple purchased NeXT back in 1996, much of NeXTStep was incorporated into OS X, including the existing class names. Cocoa Touch was introduced as the iOS equivalent of Cocoa; some classes are available in both Cocoa and Cocoa Touch, though there are also a large number of classes unique to each platform. Two-letter prefixes like NS and UI (for User Interface elements on iOS) are reserved for use by Apple.
来源:使用Objective-C编程
其他回答
Cocoa框架的原始代码来自NeXTSTEP库基金会和AppKit(这些名称仍然被苹果的Cocoa框架使用),NeXTSTEP的工程师选择用NS作为他们的符号前缀。
因为Objective-C是C的扩展,因此不像c++那样有名称空间,符号必须有一个唯一的前缀,这样它们就不会发生冲突。这对于在框架中定义的符号尤为重要。
如果您正在编写一个应用程序,以便您的代码可能只使用您的符号,那么您不必担心这个问题。但是如果您正在编写供他人使用的框架或库,您还应该为您的符号添加一个唯一的前缀。CocoaDev有一个页面,许多Cocoa社区的开发人员列出了他们“选择”的前缀。您可能也会发现这个SO讨论很有帮助。
它来自NeXTSTEP传统。
NS基本上来自NextSTEP,这是苹果收购Next时最初的操作系统,后来成为Mac OS X。
我想解释一些其他的东西,这就是为什么需要它。
在c++中有命名空间,几乎所有的东西都放在std中
这就是为什么要使用std::string。
使用名称空间,这样就不会出错,而且可以编写自己的类字符串,而不会与系统字符串冲突。
Objective-C是C的超集,但它不包括命名空间,出于同样的原因,所有系统类都以NS或其他奇怪的前缀作为前缀。
这与所有DirectX类都以D3D为前缀,以及所有OpenGL类都以gl为前缀是一样的。
这意味着你不应该使用NS来命名你自己的类,当你在Core Animation中看到NS, CA或在Core Graphics中看到CG时,你就知道这是对系统框架的调用。
Swift改变了这一惯例,因为Swift支持命名空间,并将其核心类型(如String)映射到NS等等物。
Bill Bumgarner又名@bbum,谁应该知道,他在2005年的CocoaBuilder邮件列表上写道:
Sun是在NS前缀开始发挥作用之后才进入的。NS前缀出现在从NeXTSTEP 3.0到NeXTSTEP 4.0(也称为OpenStep)的公共api中。4.0之前,a 少数符号使用NX前缀,但大多数类提供 系统库根本没有前缀——List, Hashtable, 看来,等等……
似乎每个人都同意,NX (NeXT)这个前缀在1993/1994年之前一直被使用,苹果的文档中写道:
1994年9月发布的官方OpenStep API是第一个将API分离为Foundation和Application Kit的API,并且第一个使用“NS”前缀的API。
来自Cocoa_(API)维基百科:
(重点)
Cocoa classes begin with the acronym "NS" (standing either for the NeXT-Sun creation of OpenStep, or for the original proprietary term for the OpenStep framework, NeXTSTEP): NSString, NSArray, etc. Foundation Kit, or more commonly simply Foundation, first appeared in OpenStep. On Mac OS X, it is based on Core Foundation. Foundation is a generic object-oriented library providing string and value manipulation, containers and iteration, distributed computing, run loops, and other functions that are not directly tied to the graphical user interface. The "NS" prefix, used for all classes and constants in the framework, comes from Cocoa's OPENSTEP heritage, which was jointly developed by NeXT and Sun.
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 缓冲区是什么意思?