从其他 class 访问变量?

Access variable from other class?

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

AppDelegate:

- (void)setVariable {

    var1 = @"TEST";

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

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

我的班级

- (void)getVariable {

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

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

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

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

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

旁注:您提供的源代码中似乎有拼写错误。 AppDelegate *getVar * [AppDelegate alloc] init]; 缺少一个 = 和一个 [

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

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

因此您的代码如下所示:

- (void)getVariable {

     AppDelegate *getVar = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     var2 = getVar.var1;
     NSLog(@"var2: %@",var2);
}
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"]);