Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unlike Java, where a static variable is scoped for all instances of a class, <code>static</code> in C means that a variable is accessible only from within the file where it is declared. It allows you to do things like declare a static variable inside a function, which sets the value only the first time through, <a href="http://www.phanderson.com/C/static.html" rel="noreferrer">like this</a>.</p> <p>One thing you haven't mentioned is the relationship between classes A, B, and C. If they are in an inheritance hierarchy, and you're expecting the static variable to be inherited as in Java, the method described by <em>zpasternack</em> will work.</p> <p>If the three classes are unrelated, and you just want to access the value declared in A, then <code>extern</code> is a more appropriate way to go. In this case, you want to declare the variable as <code>extern</code> in ClassA.h, then define it in Class.m. As long as ClassB and ClassC import ClassA.h, they will be able to link against the same extern definition.</p> <p>One fine point is that, instead of using <code>extern</code> by itself, it's more robust to use <code>OBJC_EXPORT</code>, which is defined in objc-api.h and handles compiling under C++ as well. Here's a code sample:</p> <pre><code>// ClassA.h OBJC_EXPORT NSString* commonString; ... // ClassA.m NSString* commonString = @"OldValue"; // ClassB.m #import "ClassA.h" ... commonString = @"NewValue"; // Can be inside a function or method </code></pre> <p>Of course, using externed variables in this way creates an infamous, much-maligned <strong>global variable</strong>, which is fragile in that anyone can read or write it, and access is uncontrolled. This is the simple approach, and answers your question about using <code>static</code> vs. <code>extern</code>. However, as a design principle, the encapsulation provided by wrapping the variable with class methods is much safer, albeit more complex. In object-oriented languages, when the effect you're trying to achieve is that of a class-static method, encapsulation is probably the right way to go.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload