How can I access variables from another class?

2019-01-14 18:29发布

问题:

There is probably a very simple solution for this but I can't get it working.

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?

回答1:

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;

To make it a property:

@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:

You could expose the variable in class2 as a property. If class1 has a reference to class2, class1 can then see the variable. Honestly, though, it sounds like you're a beginner to both Objective-C and object oriented programming. I recommend you read up more on both.

Here is a place to start for object oriented programming with Objective-C.



回答3:

try making a file that holds your variables that need to be accessed throughout the app.

extern NSString *stringVariable;

@interface GlobalVariables

@property (retain, nonatomic) NSString *stringVariable;    

@end

and in the GlobalVariables.m file add

#import "GlobalVariables.h"

@implements GlobalVariables

@synthesize stringVariable;

NSString *stringVariable;

@end

And then as long as you import GlobalVariables.h into which ever .m files you need to access that variable in you can assign and access anywhere throughout your program.

EDIT

My answer that I have given above is differently not the way I would go about doing this now. It would be more like

@interface MyClass

@property (nonatomic, strong) NSString *myVariable;

@end

then in the .m file

@implementation MyClass

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

@end

Then in another class in some method I would have

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


回答4:

In "XCode" you need to make import, create object by declaring it as the property, and then use "object.variable" syntax. The file "Class2.m" would look in the following way:

#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

Thanks! :-)