BuySellAds.com

If you like my tutorials, you will love my book . It is chockful of advanced programming techniques and the only comprehensive barcode reference for serious iOS developers.
Our DNA is written in Objective-C
Jump

Shuffling an NSArray

For a project I am working on I needed to shuffle the contents of an NSArray without harming the items themselves. NSArray is a convenient container because it does not care about what you put inside. This is because you don’t (put objects into arrays), you only pretend.

You cannot add an object itself into an array but instead you always insert pointers to class instances. NSArray and its bigger cousin NSMutableArray will keep track of the pointers and memory management of the items so you don’t have to. This is a custom category for NSArray that is useful for shuffling the contents, regardless of their class type.

The header NSArray+Helpers.h:

#import
 
@interface NSArray (Helpers)
 
- (NSArray *) shuffled;
 
@end

The implementation NSArray+Helpers.m:

#import "NSArray+Helpers.h"
 
@implementation NSArray (Helpers)
 
- (NSArray *) shuffled
{
	// create temporary autoreleased mutable array
	NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[self count]];
 
	for (id anObject in self)
	{
		NSUInteger randomPos = arc4random()%([tmpArray count]+1);
		[tmpArray insertObject:anObject atIndex:randomPos];
	}
 
	return [NSArray arrayWithArray:tmpArray];  // non-mutable autoreleased copy
}
 
@end

The implemented method works by adding the object references to a temporary NSMutableArray at random positions. The arithmetic is necessary that only valid positions are chosen at random. If you try to insert an object with too high an index then your app crashes with an exception.

How to use it:

#import "NSArray+Helpers.h"
 
// test shuffling
NSArray *arr = [[NSArray arrayWithObjects:@"1",@"2", @"3", @"4", nil] shuffled];
NSLog([arr description]);

You might have noticed previously that I have grown very fond of Class Categories. This is the method of choice if you want to teach existing classes new tricks.


Categories: Recipes

17 Comments »

  1. Is NSMutableArray *tmpArray auto-released because you passed the pointer to arrayWithArray?

  2. No, because I marked it as autoreleased! 😉 (After you caught me on this one)

  3. I know i’m just nit-picking now, but [NSMutableArray arrayWithCapacity:[self count]] would be a bit more readable. 😉

  4. Ok, you win. Would you consider writing a guest column for this blog?

  5. I would love to do a guest post on marketing an iPhone app.

Trackbacks

  1. Dr. Touch » Blog Archive » The Importance of Method Naming
  2. 12 Hours, 2 Guys, 6 Cups of Coffee, 1 iPhone App | mobiearth.com
  3. 12 Hours, 2 Guys, 6 Cups of Coffee, 1 iPhone App [IPhone] | TechBlogs Today
  4. 12 Hours, 2 Guys, 6 Cups of Coffee, 1 iPhone App [IPhone] | Products & Tech News
  5. 12 Hours, Two Guys, Six Cups Of Coffee, One iPhone App | Gizmodo Australia
  6. How 12 Hours, 2 Guys, 6 Cups of Coffee = 1 iPhone App [IPhone] | Products & Tech News
  7. How 12 Hours, 2 Guys, 6 Cups of Coffee = 1 iPhone App : MIDEASTA
  8. How 12 Hours, 2 Guys, 6 Cups of Coffee = 1 iPhone App | Human Interface Systems
  9. How 12 Hours, 2 Guys, 6 Cups of Coffee = 1 iPhone App | The KW Blog
  10. The Story That Inspired Us ‹ Two App Guys
  11. Array Shuffle? - iPhone Dev SDK Forum
  12. Mescolare un array: una categoria | iOS Dev Blog

Leave a Comment

%d bloggers like this: