Friday, 15 August 2014

objective c - iOS Set up NSTimer to call a method only on active / inactive page -



objective c - iOS Set up NSTimer to call a method only on active / inactive page -

i 1 of viewcontroller want phone call method updatevisitotslists on time criteria's , not able decide way best accomplish it.

1) every time view loaded/appeared want phone call method.

for in viewdidappear method can phone call before calling [super viewdidappear];, works, believe.

2) if user on view only, want phone call method after every 5 secs.

for this, need set nstimer. want stop timer when viewdiddisappear - don't want running unnecessary. should utilize unscheduled timer shown here , start , stop in appear & disappear methods ? in viewdidappear, phone call method, , set

nstimer *t = [nstimer scheduledtimerwithtimeinterval: 5.0 target: self selector:@selector(updatevisitotslists:) userinfo: nil repeats:no];

what best way , methodology accomplish looking ? help highly appreciated.

thanks.

updated :-

@lord zolt, per comment did next :-

//in .h @property (strong, nonatomic) nstimer *timer; // .m @synthesize timer; - (void)viewdidload { ........ [super viewdidload]; // create timer timer = [nstimer scheduledtimerwithtimeinterval:5 target:self selector:@selector(ontimercall:) userinfo:nil repeats:yes]; } -(void) viewwilldisappear:(bool)animated { [timer invalidate]; timer = nil; [super viewwilldisappear:animated]; } -(void) ontimercall: (nstimer *) _timer { // update visitor's list [self updatevisitotslists]; }

is proper ?

i recommend using timers.

create nstimer property, recommend calling invalidate on them on viewwilldisappear.

if don't phone call invalidate, when view controller dismissed or popped, won't deallocated, since nstimer maintain alive.

the code posted fine few modifications:

you don't need @synthesize properties anymore (unless overwrite both setter , getter). don't set timer nil.

edit: if want timer related screen (aka should executed when screen visible), should initialise in viewdid(will)appear , stop in viewdid(will)disappear.

ios objective-c nstimer

No comments:

Post a Comment