365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Apr 8

Day 39: addObjectIfNotNil:

NSMutableArray throws an exception when you try to insert nil into an array. Often I find that I am retrieving possible objects from somewhere and I don’t want to convolute my code by checking for nil all the time or wrapping them in those ugly try-catch statements. So I do what I always do in cases like these:

@implementation NSMutableArray (NSArray_365Cocoa)
- (void)addObjectIfNotNil:(id)obj
{
  if (obj != nil)
    [self addObject:obj];
}
@end