views:

1815

answers:

2

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?

A: 

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 int var;
// methods...
@end

@implementation Class1
@synthesize(readwrite, nonatomic) 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];
Adam Rosenfield
The property approach is far better, IMHO
Abizern
+6  A: 

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.

unforgiven3