iPhone开发:全局变量 [英] iPhone Development: Global Variables

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

问题描述

Objective-C对我来说很新颖。我需要做一个全局变量。我有文件abc.h,abc.m,aaa.h,aaa.m,当然还有应用程序委托。



我想在abc中声明它。 h,使用让用户在abc.m中指定它,并在aaa.m中使用它。
我希望变量是一个名为x的整数。我听说我可以以某种方式使用App Delegate。
我希望在我的代码中间实现abc.m中的赋值变量。
因为我是新手,请简单点!



感谢您的提前!

解决方案

您可以在应用程序委托中使用属性,因为您始终可以使用以下应用程序委托实例:

  [[UIApplication sharedApplication] delegate] 

所以:

  / * AppDelegate.h * / 
@interface AppDelegate:NSObject< UIApplicationDelegate>
{
int x;
}
@property(只读)int x;
@end

/ * AppDelegate.m * /
#importAppDelegate.h
@implementation AppDelegate
@synthesize x;
@end

这样,您就可以使用:


$ b $

  [[[UIApplication sharedApplication] delegate] x] 

另一种方法是使用全局变量,在abc.h文件中声明为extern,并在abc.m文件中定义。

  / * abc.h * / 
extern int x;

/ * abc.m * /
int x = 0;

这样,其他文件将只能通过包含abc.h来访问x。
extern 告诉编译器该变量将在稍后定义(例如在另一个文件中),并且它将在链接时解析。


I am very new to Objective-C. I need to make a global variable. I have the files abc.h, abc.m, aaa.h, aaa.m and of course, the app delegate.

I want to declare it in abc.h, use have the user assign it in abc.m and it be used in aaa.m. I want the variable to be an integer named x. I heard that I can use the App Delegate Somehow. I want the assigning variable in abc.m to be implemented in the middle of my code. Since I'm new, please make it simple!!

Thanks in Advance!

解决方案

You can use a property in your application delegate, as you can always get the app delegate instance with:

[ [ UIApplication sharedApplication ] delegate ]

So:

/* AppDelegate.h */
@interface AppDelegate: NSObject < UIApplicationDelegate >
{
    int x;
}
@property( readonly ) int x;
@end

/* AppDelegate.m */
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize x;
@end

This way, you'll be able to use:

[ [ [ UIApplication sharedApplication ] delegate ] x ]

Another approach is to use a global variable, declared as extern in your abc.h file, and defined in the abc.m file.

/* abc.h */
extern int x;

/* abc.m */
int x = 0;

This way, other files will be able to access x, only by including abc.h. extern tells the compiler that the variable will be defined later (e.g. in another file), and that it will be resolved at link time.

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

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