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

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

问题描述

根据 第202页的第206页的Cocoa Programming for Mac OS X:

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.

一个更好的设计是一个简单的Singleton类与这些定义?还是真的是去全球的正确的最佳做法?

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天全站免登陆