【问题标题】:How can I access variables from another class?如何访问另一个类的变量?
【发布时间】:2010-10-14 02:36:03
【问题描述】:

可能有一个非常简单的解决方案,但我无法让它工作。

我的 Cocoa 文件中有多个类。在其中一个类class1 中,我创建了一个变量,我也需要在另一个类class2 中使用它。有没有一种简单的方法可以在class2 中导入这个变量?

【问题讨论】:

  • “我的 Cocoa 文件中有多个类。”通常的方法是为每个类创建一对文件(MyClass.h、MyClass.m)。您可以通过右键单击项目中的组并单击添加文件来执行此操作。您将创建 .m,而 .h 将免费提供。
  • 直接访问实例变量是一个非常糟糕的主意。使用属性,合成访问器或编写自己的访问器。直接变量访问会破坏诸如 KVO 和 Mac OS X 上的绑定之类的东西,这不是好的 OO 实践。

标签: objective-c cocoa class import


【解决方案1】:

您可以将变量设为公开,也可以将其设为属性。例如,公开:

@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];

【讨论】:

  • 属性方法要好得多,恕我直言
【解决方案2】:

您可以将 class2 中的变量作为属性公开。如果 class1 有对 class2 的引用,则 class1 可以看到该变量。不过,老实说,听起来您是 Objective-C 和面向对象编程的初学者。我建议您阅读这两个方面的更多内容。

Here is a place 开始使用 Objective-C 进行面向对象编程。

【讨论】:

  • “stackoverflow.com”是否仅适用于高级用户?如何定义谁是初学者,谁不是。这家伙没有提出在哪里学习 Objective-C 的问题。
  • 老实说同意@DariusMiliauskas:P
  • Stackoverflow 适合所有人,我相信这个问题是有道理的,它可以帮助其他可能寻找上述问题答案的人!
【解决方案3】:

尝试创建一个文件来保存需要在整个应用程序中访问的变量。

extern NSString *stringVariable;

@interface GlobalVariables

@property (retain, nonatomic) NSString *stringVariable;    

@end

并在 GlobalVariables.m 文件中添加

#import "GlobalVariables.h"

@implements GlobalVariables

@synthesize stringVariable;

NSString *stringVariable;

@end

然后,只要您将 GlobalVariables.h 导入到您需要访问该变量的任何 .m 文件中,您就可以在整个程序中的任何位置分配和访问。

编辑

我上面给出的答案与我现在要做的不同。 会更像

@interface MyClass

@property (nonatomic, strong) NSString *myVariable;

@end

然后在.m文件中

@implementation MyClass

@sythesize = myVariable = _myVariable; // Not that we need to do this anymore

@end

然后在另一个类中以某种方法我会有

// .....
MyClass *myClass = [[MyClass alloc] init];
[myClass setMyVariable:@"My String to go in my variable"];
// .....

【讨论】:

  • [[MyClass alloc] init] 将给出一个新实例!
【解决方案4】:

在“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

谢谢! :-)

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 2015-03-11
    • 2011-07-20
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多