Skip to content

Instantly share code, notes, and snippets.

@mysteriouspants
Created August 19, 2011 16:49
Show Gist options
  • Save mysteriouspants/1157309 to your computer and use it in GitHub Desktop.
Save mysteriouspants/1157309 to your computer and use it in GitHub Desktop.
Sign that I'm Going Nuts. I'm putting corrupted lyrics to Tower of Power songs into my source code. With diacriticals.
//
// NSArray+Chunky.h
//
// Created by Christopher Miller on 8/19/11.
// Copyright 2011 FSDEV. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSArray (Chunky)
/**
* YOU GOT 'TA CHUNKIFY!!! JUST LIKE A BOW-LEGGÈD MONKEY!!! YOU GOT 'TA CHUNKIFY!!! NSAAAAAAARRRRAAAAYAH!
*
* Takes sth like this:
*
* ( 1, 2, 3, 4, 5, 6, 7, 8, 9 )
*
* and then a call like this:
*
* [myArray chunkifyWithMaxSize:3];
*
* will return sth like this:
*
* ( ( 1, 2, 3 ), ( 4, 5, 6 ), ( 7, 8, 9 ))
*/
- (NSArray *)chunkifyWithMaxSize:(NSUInteger)size;
@end
//
// NSArray+Chunky.m
//
// Created by Christopher Miller on 8/19/11.
// Copyright 2011 FSDEV. All rights reserved.
//
#import "NSArray+Chunky.h"
@implementation NSArray (Chunky)
- (NSArray *)chunkifyWithMaxSize:(NSUInteger)size
{
NSAutoreleasePool * pool0 = [[NSAutoreleasePool alloc] init];
NSMutableArray * chunks = [[NSMutableArray alloc] init];
NSMutableArray * chunk = [NSMutableArray array];
for (id object in self) {
if ([chunk count] == size) {
[chunks addObject:chunk];
chunk = [NSMutableArray array];
}
[chunk addObject:object];
}
if ([chunk count] > 0)
[chunks addObject:chunk];
[pool0 release];
return [NSArray arrayWithArray:[chunks autorelease]];
}
@end
@monyschuk
Copy link

I'd go with something like this:

    - (NSArray *)subarrayForChunk:(NSUInteger)chunk length:(NSUInteger)length {
        NSRange chunkRange = NSMakeRange(chunk * length, length);
        NSRange allObjectsRange = NSMakeRange(0, self.count);

        NSRange intersectionRange = NSIntersectionRange(chunkRange, allObjectsRange);

        if (intersectionRange.length > 0) {
            return [self subarrayWithRange:intersectionRange];
        } else {
            return nil;
        }
    }

    - (NSArray *)chunkifyWithMaxSize:(NSUInteger)size {
        NSUInteger chunk = 0;
        NSMutableArray *chunks = @[].mutableCopy;
        while (1) {
            NSArray *chunkArray = [self subarrayForChunk:chunk++ length:size];
            if (chunkArray.count == 0) break;

            [chunks addObject:chunkArray];
        }
        return chunks;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment