Objective-C: Where to initialize a delegate -


i don´t understand how use delegation pattern in obj-c. have class: diggamecontrollayer.h , in it´s header define protocol 1 required method users of class needs implement. create delegate property use within code other property delegate responsibility of moveobjecttoposition: method should do. far hope.

//diggamecontrollayer.h @protocol diggamecontrollayerdelegate <nsobject> -(void) moveobjecttonewposition: (ccsprite *)object atspeed:(float)movespeed; @end  @property (assign) id <diggamecontrollayerdelegate> delegate; 

then class using class (in case digcharacter) says adheres diggamecontroldelegate protocol

@interface diggoblinplayer : digcharacter <diggamecontrollayerdelegate> 

but don´t understand initialize , set delegate property declared? cause nothing when use in diggamecontrollayer since it´s null

[self.delegate moveobjecttonewposition:object atspeed:movespeed]; 

you can pass delegate in init method so:

diggoblinplayer* player; player = [[diggoblinplayer alloc] initwithname:(nsstring*)name delegate:self]; 

or set separately:

diggoblinplayer* player; player = [[diggoblinplayer alloc] initwithname:(nsstring*)name]; player.delegate = self; 

which style choose depends on if want/need delegate, or if want able change/reset later on.

in cases don't want delegate public property; you'd use first style.

you see lot of example of in ios sdk here.

note self --which example, , other object of course-- needs implement delegate. , name made up.


Comments