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;
}