Objective C, persistent Class variables

Discussion in 'Mac Programming' started by KnightWRX, Apr 17, 2011.

  1. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #1
    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.
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    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.
     
  3. thread starter macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #3
    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.
     
  4. macrumors 603

    Joined:
    Aug 9, 2009
    #4
  5. macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #5
    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.
     

Share This Page