1

在 Actionscript 中,您可以使用如下全局变量:

var number : Number = 15;

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

4

1 回答 1

6

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

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

// 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 是有益的。

于 2009-07-11T16:04:10.647 回答