从另一个类访问变量?

时间:2015-02-06 19:36:16

标签: ios objective-c macos class

我有一个在我的AppDelegate中设置的变量(var1)。我有另一个类MyClass,我想从AppDelegate中检索变量。我可以设置MyClass中定义的变量(var2):

的AppDelegate:

- (void)setVariable {

    var1 = @"TEST";

    MyClass *setVar = [[MyClass alloc] init];
    setVar.var2 = var1;
    NSLog(@"var2: %@",setVar.var2);  // Outputs TEST
}

当我尝试在MyClass中获取变量时,它是空的:

MyClass的

- (void)getVariable {

     AppDelegate *getVar = [[AppDelegate alloc] init];
     var2 = getVar.var1;
     NSLog(@"var2: %@",var2);  // Outputs NULL
}

如果我还包含[getVar setVariable];,但这不是我想做的事情,它会起作用,因为它会将变量设置为静态值。我试图获取之前在AppDelegate中设置的变量。

3 个答案:

答案 0 :(得分:0)

如果您创建了应用委托的新实例,则无法检索更新的属性值;你只会看到默认值。

相反,您可能希望使用已分配给应用程序的应用程序委托:

[(AppDelegate *)[[UIApplication sharedApplication] delegate] var1];

旁注:您提供的源代码中似乎存在拼写错误。 AppDelegate *getVar * [AppDelegate alloc] init];遗漏了=[

答案 1 :(得分:0)

执行AppDelegate *getVar = [[AppDelegate alloc] init];时,您将创建AppDelegate类的新实例。默认情况下,这不会为var1分配值。这就是为什么在你拨打[getVar setVariable];一次后,它会输出正确的值。

假设您已经在委托给您的应用程序的AppDelegate实例上调用setVariable,您可以从检索AppDelegate的实例开始:(AppDelegate *)[[UIApplication sharedApplication] delegate];

所以你的代码看起来像是:

- (void)getVariable {

     AppDelegate *getVar = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     var2 = getVar.var1;
     NSLog(@"var2: %@",var2);
}

答案 2 :(得分:0)

You are again creating another instance of AppDelegate which is already there in memory.

You need to access the same same AppDelegate object what it was created at beginning of your app.

You can access AppDelegate object and its property using following code.


id appDelegate = [[UIApplication sharedApplication] delegate];

 NSLog(@"[appDelegate valueForKey:var1]=%@",[appDelegate valueForKey:@"var1"]);