Our DNA is written in Objective-C

Wait a Week

Moshe asks:

“How can make my app show a message 1 week after an event? I want to show an alert view the first time the app is launched after at least 1 week has expired and the event is still true.”

This technique can be used for any kind of action you don’t want to do right away or somehow should be based on a value determined in a previous run of your app.

BSA Banner

This is how I would do it: use NSUserDefaults for storing the value. Since you cannot save NSDate in the user defaults you have to use the trick of instead saving the number of seconds since 1970 which is NSTimeInterval or actually a double value.

//Instantiate NSUsersDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (event)
	NSTimeInterval prevTimestamp = [defaults doubleForKey:@"FirstDate"];
	NSDate *now = [NSDate date];
	if (!prevTimestamp) // this is the first time, there is no previously saved time stamp
		// save current timestamp as double
		[defaults setObject:[NSNumber numberWithDouble:[now timeIntervalSince1970]] forKey:@"FirstDate"];
		NSTimeInterval secsSinceFirstDate = [now timeIntervalSince1970] - prevTimestamp;
		if (secsSinceFirstDate>(7*24*60*60))  // quick & dirty 1 week
			NSLog(@"show alert, %f secs passed since first date saved", secsSinceFirstDate);

Take note that this method employs the quick&dirty method of date arithmetic. If it is important to be calender exact (i.e. also take care of switching to/from daylight savings time) you need to use the more elaborate method I explained previously.

Categories: Q&A


  1. Just implemented this in my app. Thanks for the nifty piece of code!

Leave a Comment

%d bloggers like this: