【问题标题】:Accessing variables in another class访问另一个类中的变量
【发布时间】:2012-02-23 23:09:25
【问题描述】:

我在 class1 中有整数,需要在 class2 中使用。我在 class2 的 .m 文件中导入了 class1 的 .h 文件,但我仍然无法访问该变量。不知道为什么! :(

我什至在 class1 的 .h 文件中为每个整数创建了一个属性,并将其合成到 .m 文件中。

有谁知道问题出在哪里?

基本上,这就是我在class1.h中所拥有的

//interface here
{
    NSInteger row;
    NSInteger section;
}

@property NSInteger row;
@property NSInteger section;

这是 class1 的 .m 文件。

//implementation
@synthesize section = _section;
@synthesize row = _row;

然后在class2的实现中,我有这个

#import "Class2.h"
#import "Class1.h"

如何在类 2 的方法中访问这些整数?

【问题讨论】:

  • 你在尝试 Class1 * aClass1Var = [[Class1 alloc] init]; aClass1Var.intVal1 = 0;或者只是 Class1.intVal1 = 0; ?
  • 在 Class1.h 之前 @end 添加以下行 @property int myInt; 然后在 Class1.m 之后 @implementation 添加 @synthesize myInt; 或发布您的代码
  • 我编辑了我的问题以包含代码
  • 很好,但这并没有显示您如何尝试访问这些属性。另外,我的回答不适合你吗?

标签: objective-c xcode xcode4.2


【解决方案1】:

您需要创建 class1 的实例(对象)才能访问属性(变量)。

// Create an instance of Class1
Class1 *class1Instance = [[Class1 alloc] init];

// Now, you can access properties to write
class1Instance.intProperty = 5;
class1Instance.StringProperty = @"Hello world!";

// and to read
int value1 = class1Instance.intProperty;
String *value2 = class1Instance.StringProperty;

编辑

// Create an instance of Class1
Class1 *class1Instance = [[Class1 alloc] init];

// Now, you can access properties to write
class1Instance.row = 5;
class1Instance.section = 10;

// and to read
NSInteger rowValue = class1Instance.row;
NSInteger sectionValue = class1Instance.section;

【讨论】:

  • 如果这个答案对你有用,你应该检查(打勾)它以奖励@sch
【解决方案2】:

我分享了类似问题的答案(查看How can I access variables from another class?)。不过,我可以在这里重复一遍。

在“XCode”中,您需要进行导入,通过将其声明为属性来创建对象,然后使用“object.variable”语法。文件“Class2.m”如下所示:

#import Class2.h
#import Class1.h;

@interface Class2 ()
...
@property (nonatomic, strong) Class1 *class1;
...
@end

@implementation Class2

//accessing the variable from balloon.h
...class1.variableFromClass1...;

...
@end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2023-04-07
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    相关资源
    最近更新 更多