这可能有一个非常简单的解决方案,但我无法让它起作用。
在我的Cocoa文件中,我有多个类。在其中一个类class1
中,我创建了一个变量,我需要在另一个类class2
中也使用它。有没有一种简单的方法可以在class2
中导入这个变量?
这可能有一个非常简单的解决方案,但我无法让它起作用。
在我的Cocoa文件中,我有多个类。在其中一个类class1
中,我创建了一个变量,我需要在另一个类class2
中也使用它。有没有一种简单的方法可以在class2
中导入这个变量?
你可以将变量声明为public,或将其转换为属性。例如,要将其声明为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];
extern NSString *stringVariable;
@interface GlobalVariables
@property (retain, nonatomic) NSString *stringVariable;
@end
并且在GlobalVariables.m文件中添加
#import "GlobalVariables.h"
@implements GlobalVariables
@synthesize stringVariable;
NSString *stringVariable;
@end
只要在需要访问该变量的任何.m文件中导入GlobalVariables.h,您就可以在程序中的任何位置进行分配和访问。
编辑
我之前提供的答案不是我现在做这件事情的方式。更好的方式应该是:
@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"];
// .....
#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
谢谢!:-)