开发者

Get integer value from another class

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 do it?

MainViewClass : UIViewController {
int score;
}


#import "MainViewClass.h"
OtherClass : MainViewClass{

}

Then in the .m of OtherClass i want to be able to use the variable score.

How do i do this?

I have searched around the internet, and have tried several things to try to get it to work will no success.

Thanks for looking! Have a wonderful day.


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;


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.)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜