CocoaDev

Edit AllPages

Some handy addenda to NSArray, everybody’s favorite Cocoa OrderedCollection. Some are for symmetry, some are for kicks, all are for free. Enjoy.

Source for NSArray+CocoaDevUsersAdditions.h :

#import <Foundation/Foundation.h>

@interface NSArray(CocoaDevUsersAdditions)

/* please criticize these…. */

// Unnecessary; can use -doesContain from NSComparisonMethods.

// NOTE: results array contains instance of NSNull where result of performing selector is nil // a collection here is anything responding to -objectEnumerator

// Quick-and-dirty NSTableView delegate methods // useful mainly for uncomplicated single-column tableViews

@end

Source for NSArray+CocoaDevUsersAdditions.m :

#import “NSArray+CocoaDevUsersAdditions.h”

@implementation NSArray(CocoaDevUsersAdditions)

+(NSArray *)arrayWithClonesOf:(id)object count:(unsigned)count { NSMutableArray * cloneArray = [NSMutableArray arrayWithCapacity:count]; while([cloneArray count] < count) { [cloneArray addObject:object]; } return [NSArray arrayWithArray:cloneArray]; }

-(BOOL)isEmpty { return [self count] == 0; }

-(BOOL)isNotEmpty { return [self count] != 0; }

-(id)firstObject { return [self objectAtIndex:0]; }

-(NSArray *)arrayByRemovingObjectAtIndex:(unsigned)index { NSMutableArray * newArray = [NSMutableArray arrayWithArray:self]; [newArray removeObjectAtIndex:index]; return [NSArray arrayWithArray:newArray]; }

-(NSArray *)arrayByRemovingObjectsInRange:(NSRange)range { NSMutableArray * newArray = [NSMutableArray arrayWithArray:self]; [newArray removeObjectsInRange:range]; return [NSArray arrayWithArray:newArray]; }

-(NSArray *)arrayByRemovingObject:(id)anObject { if(anObject == nil) { return [[self copy] autorelease]; } //dodge an exception NSMutableArray * newArray = [NSMutableArray arrayWithArray:self]; [newArray removeObject:anObject]; return [NSArray arrayWithArray:newArray]; }

-(NSArray *)reversedArray { return [[self reverseObjectEnumerator] allObjects]; }

// Quick-and-dirty NSTableView delegate methods // useful mainly for uncomplicated single-column tableViews

@end

Category:CocoaDevUsersAdditions