Cocoa/Objective-C 中的全局变量? [英] Global Variables in Cocoa/Objective-C?

查看:25
本文介绍了Cocoa/Objective-C 中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Cocoa Programming for Mac OS X,第 3 版,第 202 页(第 13 章):

According to Cocoa Programming for Mac OS X, 3rd Edition, on page 202 (chapter 13):

您将注册、阅读和在几个类中设置默认值你的申请.为了确保你总是用同一个名字,你应该在一个单个文件,然后简单地#import将该文件放入您所在的任何文件中使用名称.有几种方式去做这个.例如,您可以使用C 预处理器的 #define 命令,但大多数 Cocoa 程序员使用全局用于此目的的变量.

You will be registering, reading, and setting defaults in several classes in your application. To make sure that you always use the same name, you should declare those strings in a single file and then simply #import that file into any file in which you use the names. There are several ways to do this. For example, you could use the C preprocessor’s #define command, but most Cocoa programmers use global variables for this purpose.

这真的是正确的最佳实践吗?全局变量?这对我来说似乎很疯狂——与我所学的一切背道而驰.

Is this really the correct best practice? Global variables? That seems insane to me – counter to everything I’ve ever been taught.

一个更好的设计是定义了这些的简单单例类吗?或者它真的是走向全球的正确最佳实践吗?考虑到许多人认为单身人士是穿着漂亮衣服的全球人,还有比这两种模式更好的模式吗?

Would a better design be a simple Singleton class with these defined? Or is it really the correct best practice to go global? Is there a better pattern than either, given that many people consider Singletons to be globals in a pretty dress?

推荐答案

全局变量或单例将在这里完成同样的事情.两者都可用于转换 Cocoa 中的关键"名称,如果将其拼错为编译器错误,则不会引发编译器错误.这是主要目的.全局变量更容易一些,尽管它需要更少的输入.

Global variables or a singleton will accomplish the same thing here. Both can be used to turn 'key' names in Cocoa that won't throw a compiler error if it's misspelled into a compiler error. That's the main purpose. Global variables are a bit easier though seeing as it requires less typing.

而不是这样做:

[myArray setObject:theObject forKey:MyGlobalVariableKeyName];

您必须按照以下方式做一些事情:

You'd have to do something along the lines of:

[myArray setObject:theObject 
            forKey:[[MySingletonVariableClass getInstance] myVariableKeyName];

全局变量本质上是更少的输入以获得相同的效果.

Global variables are essentially less typing for the same effect.

这篇关于Cocoa/Objective-C 中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆