blacksoul
blacksoul

Reputation: 43

Accessing an instance variable from another class -- can I use a class method?

I need to access to a NSMutableArray, in class1, from another class (class2). The solution I tried was to create a class method in class1 and call it from class2. Obviously, it is not possible because this is a restriction of class methods. I cannot figure out the solution. What can I do?

Upvotes: 3

Views: 1338

Answers (3)

madmik3
madmik3

Reputation: 6973

Generally you expose needed instance variables through properties.

This link covers properties.

http://cocoacast.com/?q=node/103

Once the correct variables are exposed then simply pass a reference to the needed class to a given method.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Not surprisingly, you need an instance in order to access an instance variable. You can make that instance a singleton if it fits your design, or make the variable you increment static rather than ivar, which will make it accessible directly from a class method.

If there are multiple instances that you need to access from a class method, you need some sort of a registry for your objects, such as an NSDictionary that maps your objects by keys.

Upvotes: 2

Adam
Adam

Reputation: 26907

Passing the instance variable to a class method as a parameter should solve the problem. Edit: If class1 and class2 are just instances then you will need a class variable.

Upvotes: 1

Related Questions