2013-02-01 67 views
0

我有一个在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 



} 
+0

只是声明AppDelegate * appDelegate;在.h文件中。然后在viewdidload中写下appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];所以你可以在整个文件中访问appDelegate。 –

+0

当我在viewDidLoad中使用它时,我得到了使用未声明的标识符appDelegate错误 – Sindhia

+0

如果你看到那个警告,那么你的代码有一些严重错误。请发布相关代码的相关位(以及声明AppDelegate的头文件)。 – trojanfoe

回答

0

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

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

BUt我不想写AppDelegate * myLocalPointerToAppDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];无需编写的AppDelegate * myLocalPointerToAppDelegate =(AppDelegate中*)[[UIApplication的sharedApplication]委托];:[@ “%@”,ENAME的NSString stringwithFormat] 任何实例名称is.I要访问像appdelegate.name =其变量每次; 声明只有一次 – Sindhia

+0

@Sindhia你应该创建一个新的会话,只要你需要它.. –

0

为此,在类中创建一个方法,其中你想用AppDelegate的对象,

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

然后,无论你在哪里你想在该类中使用AppDelegate的对象,你可以使用它,如[self appdelegate].name

1

in Appdelegate make方法。

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

然后就的appdelegate导入您的控制器头文件,并使用

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

也许这会帮助你。

0

或者您也可以在plist文件创建AppDelegate的对象,那么你可以用它在每个控制器...

1

从你已编辑下给出的贴码,看来你的问题,你刚才宣布的AppDelegate *的appdelegate; .h

并在.m中使用“appDelegate”而不是“appdelegate”。

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

0

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

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

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