Tag Archives: NSComparisonResult

NSDate Objects in Objective C

Here we will look at using NSDate objects, how to manipulate them and compare a date to the current date to see if it is past present or future.

In the example application I setup a simple registration for an app that is time based. After a pre determined number of seconds the app registration expires. We also examine NSUserDefaults for persistent storage and how to check for a valid registration flag whenever the app runs.

Here’s the Xcode project file

- (void) registrationCheckMethod {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

BOOL registered =[defaults boolForKey:@"registered"];

NSDate *expirationCheck = [defaults objectForKey:@"expirationDate"];

if (registered) {

NSDate *todaysDate = [NSDate date];

NSComparisonResult result = [todaysDate compare:expirationCheck];

if(result==NSOrderedAscending) {

NSLog(@”Expiration is in the future”);

NSDate *todaysDate = [NSDate date];

dateLabel.text = [NSString stringWithFormat:@"%@", todaysDate];

}

else if(result==NSOrderedDescending) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Warning” message:@”App registration has expired. Please register again” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

[alert show];

getDateBtn.enabled = NO;

}

}

if (!registered) {

NSLog(@”app is not registered”);

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Warning” message:@”App is not registered” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

[alert show];

getDateBtn.enabled = NO;

}

}