全局声明AppDelegate

时间:2013-02-01 09:45:47

标签: iphone appdelegate

我在Appdelegate中定义了一个全局变量。我希望在其他控制器中使用。 我可以这样使用:

AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
  appdelegate.name=[NSString stringwithFormat:@"%@",ename];

但是,无论我想在viewController中访问appdelegates变量,我每次都必须使用AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];,它会发出警告消息,例如'AppDelgate的本地声明隐藏实例变量'。所以我有一种方法可以只声明它一旦在ViewController中多次访问它。我怎么能摆脱这个警告?

编辑:

.h :
#import "AppDelegate.h"

@interface More : UIViewController
{

    AppDelegate *appdelegate;
}
.m:
- (void)viewDidLoad
{
    [super viewDidLoad];

    appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate]; //error :Use of undeclared identifier appDelegate



}

6 个答案:

答案 0 :(得分:1)

在Appdelegate make方法中。

+(AppDelegate*)sharedInstance
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

然后只需在控制器头文件中导入appdelegate并使用

[AppDelegate sharedInstance]. name = [NSString stringwithFormat:@"%@",ename];;

也许这会对你有帮助。

答案 1 :(得分:1)

根据您在编辑下发布的已发布代码,您的问题似乎就是您刚刚宣布AppDelegate * appdelegate;在.h

并在.m。

中使用“appDelegate”而不是“appdelegate”

它显然是一个未定义的变量,不是吗?!

答案 2 :(得分:0)

如果您的问题只是警告,请将指针的本地名称更改为appDelegate:

AppDelegate *myLocalPointerToAppDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
  myLocalPointerToAppDelegate.name=[NSString stringwithFormat:@"%@",ename];

答案 3 :(得分:0)

为此,在要使用AppDelegate对象的类中创建一个方法,

-(AppDelegate *)appdelegate
{
    (AppDelegate *)[[UIApplication sharedApplication]delegate];
}

然后,无论您想在该类中使用AppDelegate的对象,都可以像[self appdelegate].name一样使用它。

答案 4 :(得分:0)

或者您可以在plist文件中创建AppDelegate对象,然后您可以在每个控制器中使用它...

答案 5 :(得分:0)

非常差的样式:实例变量应始终以下划线开头。例如,_appDelegate。在实例方法中,使用实例变量的名称自动引用self->。例如,当你有一个实例变量“appDelegate”时写“appDelegate”实际上意味着自我> appDelegate。这就是为什么你有警告:引入一个名为appDelegate的变量意味着在源代码中使用“appDelegate”现在引用局部变量而不是实例变量。那是在惹麻烦。 (“要求麻烦”意味着“任何有经验的程序员都会告诉你这迟早会导致一个无法修复的错误”)。只需添加一个变量,您就可能改变了许多代码行的含义。使用下划线对所有实例变量进行前缀解决了这个问题。

这正是编译器警告你的原因:编译器发现你只是挖了一个洞,你最终会陷入其中。

你有一个名为appDelegate或_appDelegate的实例变量也很奇怪,因为你应该通过调用[[UIApplication sharedApplication] delegate]获得appDelegate。

相关问题