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.
Share
Once you have an instance of a class, you can store it in a variable, pass it to other methods, and use it there:
…
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:
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:In C, a
staticvariable 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 ofClassWithSharedFoo, but can’t be accessed or modified elsewhere except by the provided class methods.