Loading nib and instantiating view with UIDatePicker take a lot of time

501 Views Asked by At

I have simple xib with two views: container view with date picker and toolbar with bar buttons. I use it as inputView and inputAccessoryView for my input fields (<UIKeyInput>). But I've faced with performance issue: I've noticed that loading nib of this xib file and instantiating a view from nib takes ~500ms (calculated with Time Profiler instruments tool). So, instead of adding date picker to xib I create it programmatically and vuela!, instantiating takes only ~30ms. Code example pretty straightforward:

- (void)initialize
{
    NSString * className = NSStringFromClass(self.class);
    UINib * nib = [UINib loadCachedForKey:className];
    [classNib instantiateWithOwner:self
                           options:nil];    
    _contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _contentView.frame = self.bounds;
    [self addSubview:_contentView];
}

where [UINib loadCachedForKey:] is my category, which implementation is as simple as method name sounds so I think posting it here is useless.

I also have a similar xib but with UIPicker and it is instantiated fast (~70ms). Adding date picker programmatically did work for me, but the questions are
did I do something wrong or is it normal behavior ?

1

There are 1 best solutions below

0
On

Better not to use xib file in this, use programmatically in adding date picker: Try this if it is useful for you:

- (IBAction)btnClicked:(id)sender {
    UIDatePicker *datepicker=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 300)];
    datepicker.datePickerMode = UIDatePickerModeDate;
    datepicker.hidden = NO;
    datepicker.date = [NSDate date];

    [datepicker addTarget:self
                   action:@selector(LabelChange:)
         forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datepicker]; //this can set value of selected date to your label change according to your condition


    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"M-d-yyyy"]; // from here u can change format..
    _selectedDate.text=[df stringFromDate:datepicker.date];
}
- (void)LabelChange:(id)sender{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"M-d-yyyy"];
    _selectedDate.text = [NSString stringWithFormat:@"%@",
                          [df stringFromDate:datepicker.date]];
}