objective c - Correct way to display current date/time in iOS app and keep it up to date -


i'm wondering out of theory/performance side of things, if needed display current date/time in uilabel or something, , keep date (say, down minute), correct way so?

i've seen various examples online of "clock" apps have recursive method runs 1 second delay between invocations. option create repeatable timer , add run loop. there variety of other ways well. there 1 way better others?

the recursive method not great idea.

use nstimer approach. create repeating timer in viewdidappear , invalidate timer in viewdiddisappear (to avoid retain cycle, a.k.a. strong reference cycle). example, assuming have timer property:

@property (nonatomic, strong) nstimer *timer; 

you schedule , invalidate timer follows:

- (void)viewdidappear:(bool)animated {     [super viewdidappear:animated];      self.timer = [nstimer scheduledtimerwithtimeinterval:1.0 target:self selector:@selector(handletimer:) userinfo:nil repeats:yes]; }  - (void)viewdiddisappear:(bool)animated {     [super viewwilldisappear:animated];      [self.timer invalidate];     self.timer = nil; }  - (void)handletimer:(nstimer *)timer {     // update label here } 

if don't release and/or invalidate timer, maintain strong reference controller , can end strong reference cycle. , cannot resolve strong reference cycle in dealloc (because dealloc not called until controller has no more strong references; presence of repeating nstimer has not been invalidated prevent dealloc ever getting called), why in viewdiddisappear.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -