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

查看:220
本文介绍了在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];

您可能还会发现它有利于声明变量静态的应用程序委托。

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

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

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