Get integer value from another class

后端 未结 3 562
余生分开走
余生分开走 2020-12-22 04:41

I know i have done this before, but I just cant remember how to do it.

I have a integer, that i want to be able to change in another class of mine.

how do i

相关标签:
3条回答
  • 2020-12-22 04:52

    You create getter and setter methods (or a property with synthesized accessors) in the class with the integer, give the other class a reference to some instance of the first class, and have it use those accessors to get and set the integer.

    0 讨论(0)
  • 2020-12-22 04:55

    In your MainViewClass.h, you'll want to add your int as a property of that class.

    @property (nonatomic, readwrite) int score;
    

    Then in your MainViewClass.m, you'll want to synthesize the property using:

    @synthesize score;
    

    Now since your subclassing MainViewClass in your OtherClass you can access it's properties using some combination of the following.

    In your OtherClass.h add

    MainViewClass *mainViewClass;

    in your OtherClass.m wherever you need access to the score, you should be able to access it as such.

    mainViewClass = (MainViewClass *) self.parent;
    

    and then the score using,

    mainViewClass.score;
    
    0 讨论(0)
  • 2020-12-22 04:59

    In your example, int score is an instance variable, or ivar for short. It's a piece of data associated with any given instance of MainViewClass. By default, and for good reason, instance variables have @protected visibility, meaning that only MainViewClass and its subclasses can access it.

    Now, you made OtherClass a subclass of MainViewClass in your example, which means to access score from the same object you need only type score or self->score, and from another object that is a MainViewClass you need only type theOtherObject->score. (This sort of design exposes implementation details and so is often considered to be bad design by many coders, but for a simple use case like this you can probably get away with it. Why it's bad is a discussion that has raged for decades and is beyond the scope of this question.)

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