views:

35

answers:

2

Normally if I had Class 1 and I wanted to use it elsewhere, I would write Class1 *class1 = [[Class1 alloc] init]; to create a new instance. But what if I needed to reference variables in Class1 in another class and did not want to create a new instance, but use an existing one. How would I do that? If I call init, and create a new instance, then I will reset all variables back to 0. I understand this is very elementary, but maybe it is something I never really understood. Any help is appreciated.

A: 

Once you have an instance of a class, you can store it in a variable, pass it to other methods, and use it there:

Class1 *object1 = [[Class1 alloc] init];
[someOtherObject doSomethingWith:object1];

...

@implementation SomeOtherClass
- (void)doSomethingWith:(Class1 *)anObject {
    [anObject blah];
}
@end

Addendum

In other languages, you would want a "class variable". Objective-C doesn't have them, but you can simulate them using a static variable:

static NSString *foo;

@implementation ClassWithSharedFoo

+ (NSString *)sharedFoo {
    return foo;
}

+ (void)setSharedFoo:(NSString *)newFoo {
    if(newFoo != foo) {
        [foo release];
        foo = [newFoo retain];
    }
}

@end

Note that the methods defined here begin with a + instead of a -. This makes them class methods; that is, you send the message to the class itself, not any instance of it:

[ClassWithSharedFoo setSharedFoo:@"Foo"];
NSString *foo = [ClassWithSharedFoo sharedFoo];

In C, a static variable is like a global variable, but it is only visible within the file that it was declared in; so, it is shared by all instances of ClassWithSharedFoo, but can't be accessed or modified elsewhere except by the provided class methods.

David M.
This part I understand, but calling init reset all variables in the initwith method. I need information from the class, not a new instance.
Oh Danny Boy
Do you want a variable that is shared between all instances of the class?
David M.
Oh Danny Boy
See the newly-edited answer.
David M.
A: 

You need to give the other object a reference to that instance of Class1. You can do this by setting an instance variable, hooking up a connection in Interface Builder or passing the instance as an argument to the other object.

You're right that this is very basic, but it's also very fundamental, so it's good that you're taking the time to think about it. You might try working through a few Objective-C tutorials or sample code to see how it's done.

Chuck