Objective-C: how to declare a static member that is visible to subclasses?

前端 未结 3 736
梦谈多话
梦谈多话 2020-12-15 04:22

I\'m declaring a family of static classes that deals with a communications protocol. I want to declare a parent class that process common messages like ACKs, inline errors..

相关标签:
3条回答
  • 2020-12-15 05:13

    A workaround would be to declare the static variable in the implementation of the parent class AND also declare a property in the parent class. Then in the accessor methods access the static variable. This way you can access static variables like properties with dot syntax. All the subclasses access the same shared static variable.

    0 讨论(0)
  • 2020-12-15 05:22

    More simple. Create a pre Base class, with protected static variable. For example:

    public abstract class preBase {
    
    protected static int VariableStaticPrivate;
    

    }

    public abstract class Base : preBase{

    //Inherit VariableStaticPrivate
    //And you can use it.
    

    }

    public class DerivedOne : Base {

    //Also inherit VariableStaticPrivate
    //And you can use it.
    

    }

    0 讨论(0)
  • 2020-12-15 05:28

    If you declare a static variable in the implementation file of a class, then that variable is only visible to that class.

    You could declare the static variable in the header file of the class, however, it will be visible to all classes that #import the header.

    One workaround would be to declare the static variable in the parent class, as you have described, but also create a class method to access the variable:

    @implementation ServerParser
    
    static NSString *currentElement;
    ...
    + (NSString*)currentElement
    {
        return currentElement;
    }
    ...
    @end
    

    Then, you can retrieve the value of the static variable by calling:

    [ServerParser currentElement];
    

    Yet the variable won't be visible to other classes unless they use that method.

    0 讨论(0)
提交回复
热议问题