PDA

View Full Version : Objective C, persistent Class variables




KnightWRX
Apr 17, 2011, 07:34 PM
Hi,

I've found nothing online but file scope globals, but I'm asking anyhow just in case. Is there a way to have variables for class methods that will live beyond the scope of a call ? That is basically, a class variable instead of an instance variable so that I can set something with a call to a + method and read it back with a 2nd call to a 2nd + method ?

Right now, it works great with file scope globals, but somehow, that bothers my aesthetic senses.



chown33
Apr 17, 2011, 09:08 PM
Objective-C doesn't have class variables. At all. Google objective-c class variable and see what comes up.

File-scope statics work. So do statics defined in a function or method. Exactly like C.

KnightWRX
Apr 18, 2011, 06:13 AM
Objective-C doesn't have class variables. At all. Google objective-c class variable and see what comes up.

File-scope statics work. So do statics defined in a function or method. Exactly like C.

Yeah, the googling part I had done and the answer I came up with was the same. :( I was hoping my googling skills were not top notch in this instance.

chown33
Apr 18, 2011, 10:42 AM
Yeah, the googling part I had done and the answer I came up with was the same. :( I was hoping my googling skills were not top notch in this instance.

Next step would be checking the language reference doc:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html

Conspicuous by their absence: class variables.

jared_kipe
Apr 18, 2011, 11:05 AM
Class static variables are probably best handled by the singleton pattern.

Lets say you have a class named Fraction, add a class method named +sharedFraction that returns the same static Fraction instance every time.

I've used this in a couple of my home grown classes, and have actually added them via categories to several key apple classes such as NSNumberFormatter, so I can setup a single instance and use it anywhere in my program.

EDIT: Depending on your need, you could setup + methods with static variables in them, or even file scope static variables that are referenced by + methods.