如何访问另一个类的变量? [英] How can I access variables from another class?

查看:116
本文介绍了如何访问另一个类的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的解决方案,但我不能让它工作。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆