Search code examples
objective-ciphoneaddsubview

addSubview: method horribly slow


I am trying to initialize a ViewController from another. Here is the code written in my first ViewController:

MediasViewController.h

#import "MediasVideosViewController.h"

@interface MediasViewController : UIViewController <UIWebViewDelegate>
{
    NSArray*                    videosList; 
    MediasVideosViewController  *mediasVideosViewController;
}

@property (nonatomic, retain) NSArray*  videosList;
@property (nonatomic, retain) MediasVideosViewController*   mediasVideosViewController;


MediasViewController.m :

if (self.mediasVideosViewController == nil)
{
    MediasVideosViewController* mediasVideos = [[MediasVideosViewController alloc] initWithNibName:@"MediasVideosView" bundle:nil];
    self.mediasVideosViewController = mediasVideos;
    self.mediasVideosViewController.videosList = self.videosList;
    [mediasVideos release];
}

NSDate *start = [NSDate date];
[mediasVideosViewController.view addSubview:nil];
NSLog(@"adding nil to mediasVideosViewController.view took %f seconds", [[NSDate date] timeIntervalSinceDate:start]);


Console result :

adding nil to mediasVideosViewController.view took 4.261444 seconds

Seriously? More than 4s to add nil to mediasVideosController ? It's swings between 1s and 5s.

But if I remove this line :

self.mediasVideosViewController.videosList = self.videosList;

from MediasViewController.m, I get a really shorter loading time, like :

adding nil to mediasVideosViewController.view took 0.007613 seconds

It drives me crazy...

Does anyone have a solution?


Solution

  • When you call mediasVideosViewController.view, you are basically calling loadView for the first time. You aren't just adding a subview, you are creating the entire view with that call.

    Presumably, when you set the list of videos you are giving your loadView method a lot more work to do. This will result in the behavior you see.

    In a nutshell, check out your loadView method for clues.

    EDIT: I noticed you were loading the view controller from a NIB file, in that case you want to check viewDidLoad.