Skip to content

Instantly share code, notes, and snippets.

@jamztang
Created October 18, 2011 08:02
Show Gist options
  • Save jamztang/1294851 to your computer and use it in GitHub Desktop.
Save jamztang/1294851 to your computer and use it in GitHub Desktop.
Handy NSArray category method for splitting an NSArray
// ARC
@interface NSArray (JTArraySection)
- (NSDictionary *)dictionaryBySectionKeyPath:(NSString *)keyPath;
- (NSArray *)arrayBySectionKeyPath:(NSString *)keyPath;
@end
#import "NSArray+JTArraySection.h"
@implementation NSArray (JTArraySection)
- (NSDictionary *)dictionaryBySectionKeyPath:(NSString *)keyPath {
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *name = [obj valueForKey:keyPath];
NSMutableArray *array = [newDict objectForKey:name];
if ( ! array) {
array = [NSMutableArray array];
[newDict setObject:array forKey:name];
}
[array addObject:obj];
}];
return newDict;
}
- (NSArray *)arrayBySectionKeyPath:(NSString *)keyPath {
return [[self dictionaryBySectionKeyPath:keyPath] allValues];
}
@end
//
// NSArray+JTArraySplit.h
//
// Created by james on 10/18/11.
//
#import <Foundation/Foundation.h>
@interface NSArray (JTArraySplit)
+ (NSArray *)splitArray:(NSArray *)targetArray componentsPerSegment:(NSUInteger)componentsCount;
@end
//
// NSArray+JTArraySplit.m
//
// Created by james on 10/18/11.
//
#import "NSArray+JTArraySplit.h"
@implementation NSArray (JTArraySplit)
+ (NSArray *)splitArray:(NSArray *)targetArray componentsPerSegment:(NSUInteger)componentsCount {
NSMutableArray *splitedArray = [NSMutableArray array];
NSUInteger targetArrayCount = [targetArray count];
if (targetArrayCount > 0) {
int index = 0;
while (index < targetArrayCount) {
int length = MIN(targetArrayCount - index, componentsCount);
NSArray *subArray = [targetArray subarrayWithRange:NSMakeRange(index, length)];
[splitedArray addObject:subArray];
index = index+length;
}
return splitedArray;
} else {
// no objects inside targetArray, so just return empty array
return splitedArray;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment