ios - How to access instance from another class -


thanks in advance!

i'm new oop, problem may basic, i've searched hours , still cannot find solution.

i'm using cocos2d , box2d in project. in gamelayer.mm file, have label show current score. , there's custom sprite derived ccsprite.

now, wanna increment current score custom sprite class when property of sprite "isdead" changed true. follows:

- (void) setisdead {     isdead = 1;     // increment score } 

my question how can increment score subclass? cannot access instance or instance method of gamelayer.mm subclass. tried change function of incrementing score instance method class method, , make score global instance, got duplicate error later.

thanks advice!

you use observer design pattern here in observer listens event , performs action accordingly.

so in gamelayer.mm add observer in init function:

[[nsnotificationcenter defaultcenter] addobserver:self         selector:@selector(receiveisdeadnotification:)          name:@"spriteisdeadnotification"         object:nil]; 

and add function:

- (void) receiveisdeadnotification:(nsnotification *) notification {      if ([[notification name] isequaltostring:@"spriteisdeadnotification"])         //update label here } 

and in custom sprite ,add following line in setisdead method

-(void) setisdead{      isdead =1;      [[nsnotificationcenter defaultcenter]          postnotificationname:@"spriteisdeadnotification"          object:self]; } 

also remember remove observer in dealloc of gamelayer.mm

[[nsnotificationcenter defaultcenter] removeobserver:self]; 

this pattern reduce coupling in code instances of 1 class not trying access methods of another.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -