Created by Jamz Tang at 22 August 2011

Loading a Nib file programmatically using NSObject category

Maybe you've an IB created uitableviewcell.xib, or some kind of uiview.xib wanted to load to your code-based view controller, and you come out finding it's not that straight forward just to do this simple job according to the official Resource Programming Guide

Isn't it ideal to load a nib file using one line like

MyCustomView *cell = [MyCustomView objectWithNibNamed:@"MyCustomViewNibName"];

Add this NSObject category make this possible

/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import <Foundation/Foundation.h>

@interface NSObject (JTNibLoader)

+ (id)objectWithNibNamed:(NSString *)nibName;

@end
/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "NSObject-JTNibLoader.h"

@implementation NSObject (JTNibLoader)

+ (id)objectWithNibNamed:(NSString *)nibName {
    // Since 4.0 we can use the UINib class
    UINib *nib = [UINib nibWithNibName:nibName bundle:nil]; // nil bundle represents the +[NSBundle mainBundle]
    NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];

    __block id currentObject;
    [topLevelObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([obj isKindOfClass:[self class]]) {
            currentObject = obj;
            *stop = YES;
        }
    }];

    return currentObject;
}

@end

Easy enough?

Updates: 2013-09-17

Starting from iOS 5.0, loading a UITableViewCell is recommended to use the -[UITableView registerNib:forCellReuseIdentifier:] method.


Installation

Using CocoaPods: [?]
pod 'NSObject-JTNibLoader', '~> 0.0.1'

Clone this repository:
git clone git://gist.github.com/1578429.git NSObject-JTNibLoader

Download | More...


If you think this is useful, share this article with your friends :)

blog comments powered by Disqus

ioscodesnippet.com