如何从另一个类访问变量? [英] How can I access variables from another class?
本文介绍了如何从另一个类访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能有一个非常简单的解决方案,但我无法让它工作.
There is probably a very simple solution for this but I can't get it working.
我的 Cocoa 文件中有多个类.在其中一个类 class1
中,我创建了一个变量,我也需要在另一个类 class2
中使用该变量.有没有一种简单的方法可以在 class2
中导入这个变量?
I have got multiple classes in my Cocoa file. In one of the classes class1
I create a variable that I need to use in another class class2
as well. Is there a simple way to import this variable in class2
?
推荐答案
您可以将变量设为公开,也可以将其设为属性.例如,要公开:
You can either make the variable public, or make it into a property. For example, to make it public:
@interface Class1
{
@public
int var;
}
// methods...
@end
// Inside a Class2 method:
Class1 *obj = ...;
obj->var = 3;
使其成为属性:
@interface Class1
{
int var; // @protected by default
}
@property (readwrite, nonatomic) int var;
// methods...
@end
@implementation Class1
@synthesize var;
...
@end
// Inside a Class2 method:
Class1 *obj = ...;
obj.var = 3; // implicitly calls [obj setVar:3]
int x = obj.var; // implicitly calls x = [obj var];
这篇关于如何从另一个类访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文