开发者

Detecting problematic XIB views earlier

I had a typo in my nib name and it was blowing up later in code when I was pushing to the navigation controller. It 开发者_JS百科didn't take too long to figure it out but I thought it would be better to assert well formed earlier to make it easier to figure out. The problem is it's not nil, it just couldn't form itself properly from the nib. Is there a better assert or catch to check after initWithNib to catch problems earlier in code?

//
// typo in nib name - I want to catch before it blows up inside of pushViewController to narrow the problem
//
ENPurchaseDetailView *purchaseView = [[ENPurchaseDetailView alloc] 
    initWithNibName:@"XibWithTypoInIt" bundle:nil];
assert(purchaseView != nil);  // does not catch - it's not nil - just not well formed

// other code ...

// blows up with sigabort inside of pushViewController
[[self navigationController] pushViewController:purchaseView animated:YES];    


Create a base UIViewController class that you subclass all your other VCs from. Then you can do a number of useful assertions in the base class and not have to scatter them throughout your code. Here is one that I use

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]

// never do this stuff in production code
#ifdef DEBUG
    // make sure you didn't fat finger Xib name
    if (nibNameOrNil)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:nibNameOrNil ofType:@"nib"];
        NSAssert(path, @"Nib %@ does not exist", nibNameOrNil);
    }

    // make sure there's no problems with the Xib
    UINib *nib = [UINib nibWithNibName:nibNameOrNil bundle:nibBundleOrNil ];
    NSArray *instantiatedObjects = [nib instantiateWithOwner:nil options:nil];
    NSAssert(instantiatedObjects && [instantiatedObjects count] > 0, @"Not well formed Xib");
#endif       return self;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜