Objective-C 中的全局变量 [英] Global variables in Objective-C

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

问题描述

在 Actionscript 中,您可以拥有这样的全局变量:

In Actionscript you can have global variables like this:

var number : Number = 15;

然后在方法/函数中使用它.你如何在 Objective-c 中做到这一点,这可能吗?

And then use it in a method/function. How do you do that in Objective-c, is it possible?

推荐答案

请记住,Objective-C 是 C 的严格超集,因此您可以像在常规 C 中一样声明全局变量.首先在某个文件中声明它们在任何函数之外,然后在其他文件中使用 C extern 关键字来拉入这些变量.

Remember that Objective-C is a strict superset of C, so you can declare global variables the same way you would in regular C. First declare them in some file outside of any function, then use the C extern keyword in other files to pull those variables in.

如果您想使用的不仅仅是 C 变量,而是使用 Objective-C 对象,您可以将它们存储在应用程序的委托中.只需像往常一样将它们设置在那里,然后在需要访问变量时:

If you want to do this with more than just C variables, but rather use Objective-C objects, you can store them in the application's delegate. Simply set them there as you would normally, then whenever you need to access the variable:

// Assuming your app delegate is of class YourAppDelegate and
// has an NSString* variable called globalString:
YourAppDelegate *appDelegate = 
    (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *someGlobalString = [appDelegate globalString];

您可能还会发现在应用委托中声明变量 static 是有益的.

You may also find it beneficial to declare the variable static in the app delegate.

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

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