Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm creating some age-verification functionality for an iOS app. The user is presented with a UIDatePicker object, and the latest selectable date should be today minus 18 years. How vulnerable to inaccuracy is my code? How could it be leaner?

-(void)validateAge {

    NSDateComponents *today = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    NSInteger day = [today day];
    NSInteger month = [today month];
    NSInteger year = [today year];

    int correctYear = year - 18;

    NSDateComponents *correctAge = [[NSDateComponents alloc] init];
    [correctAge setDay:day];
    [correctAge setMonth:month];
    [correctAge setYear:correctYear];

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    UIDatePicker *agePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 240, 320, 200)];
    [agePicker setDatePickerMode:UIDatePickerModeDate];
    [agePicker setMaximumDate:[calendar dateFromComponents:correctAge]];
    [self.view addSubview:agePicker];
    return;
}
share|improve this question
Well, first of all, what about leap years ? If someone uses it on the 29th of february on a leap year, february 18 years earlier will always be 28 days long. I don't know what will happen with your code though, but I'd suggest to set up a test scenario for this situation.. – rdurand Oct 26 '12 at 13:21
I think [calendar dateFromComponents:correctAge] (third line from bottom) may crash.. – rdurand Oct 26 '12 at 13:23
That's an interesting point. I tested it by setting my system date to 29/02/2012. My datepicker set the maximum date to 01/03/1994. I think that's acceptable from a legal standpoint, as 'leaplings' can either have their birthdays on February 28th or March 1st. The app I implemented this in has been tested fairly extensively on a number of devices; no crashes yet. – Jezen Thomas Oct 26 '12 at 14:17
Well, I think you're good then ! – rdurand Oct 29 '12 at 8:44

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.