Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a instance variable from another class?

I know this is a basic questions but it some how does not work.

I have an enemy class which has in its .h an instance variable :

@interface Enemy : CCLayer
{
    CCSprite *enemy1;
    CGSize winSize ;

}

I have another class which is the game class , and which wants to get access to the enemy1. So, this game class is importing the enemy.h ,and can use its functions , BUT i cant get its pointer enemy1, i have tried with no luck :

   Enemy *enemy=[[Enemy alloc]init];
    [enemy enemy1]//error
    enemy.enemy1 //error
like image 809
Curnelious Avatar asked May 03 '26 11:05

Curnelious


2 Answers

I would suggest you should add readonly properties to access those instance variables.

@property (nonatomic,assign,readonly) CCSprite *enemy1;
@property (nonatomic,assign,readonly) CGSize winSize;
like image 168
James Holderness Avatar answered May 06 '26 02:05

James Holderness


Since ivars by default are protected (means visible only to child classes), you should first declare them as public:

@interface Enemy : CCLayer
{
@public
    CCSprite *enemy1;
    CGSize winSize ;

}

After that you will be able to access ivars via standart C syntax like this: enemy->enemy1.

But why not use properties?

like image 23
Kyr Dunenkoff Avatar answered May 06 '26 02:05

Kyr Dunenkoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!