Search code examples
ios5nsbundle

Figuring out the NSBundle used for a UIViewController


When UIViewControllers are instantiated using - (id)initWithNibName:bundle:, you can pass in a bundle.

Is there a way to for the instantiated view controller to find out what its original bundle was?

I have a container UIViewController and I would like to instantiate its child UIViewController using the same bundle the parent was created with. Aside from saving the bundle as an ivar, is there another way to get this?

ContainerViewController *pvc = [[ContainerViewController alloc] 
initWithNibName:nil bundle:[NSBundle mainBundle]];

// inside ContainerViewController:
ChildViewController *cvc = [[ChildViewController alloc] 
initWithNibName:nil bundle:parentBundle];

Solution

  • UIViewController has a property named nibBundle which contains what you are looking for:

    UIViewController class reference:

    nibBundle
    Return the name of the receiver’s nib bundle if it exists. (read-only)

    @property(nonatomic, readonly, retain) NSBundle *nibBundle

    Availability
    Available in iOS 2.0 and later.
    See Also
    - initWithNibName:bundle:
    @property nibName
    Declared In
    UIViewController.h

    So, you could use:

    ChildViewController *cvc = [[ChildViewController alloc] initWithNibName:nil bundle:self.nibBundle];