Hauwa
Hauwa

Reputation: 11

Accessing variables in another class

I have integers in a class1 that i need to use in class2. I imported the .h file for class1 in the .m file of class2, but i still can't access the variable. Don't know why! :(

I even created a property for each integer in the .h file of class1 and synthesized it in the .m file.

Anyone know what the problem is?

basically, this is what i have in class1.h

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

@property NSInteger row;
@property NSInteger section;

and this is the .m file for class1.

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

and then in the implementation of class2, i have this

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

How do i access those integers in a method in class 2?

Upvotes: 0

Views: 4244

Answers (2)

Darius Miliauskas
Darius Miliauskas

Reputation: 3514

I shared the answer for the similar issue (take a look at How can I access variables from another class?). However, I could repeat it here.

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

Upvotes: 0

sch
sch

Reputation: 27506

You need to create an instance (object) of class1 to be able to access the properties (variables).

// 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;

Edit

// 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;

Upvotes: 5

Related Questions