Skip to content

Instantly share code, notes, and snippets.

@jasonwjones
Created July 10, 2012 23:52
Show Gist options
  • Save jasonwjones/3087021 to your computer and use it in GitHub Desktop.
Save jasonwjones/3087021 to your computer and use it in GitHub Desktop.
NSArray category for getting a random index or object
//
// NSArray+Random.h
//
// Just some nice little addons for NSArray that I'm surprised don't actually exist already. Grab
// a random object or an index for a random object. Bam. Presto.
//
// Created by Jason Jones on 5/18/12.
// Copyright (c) 2012 Saxifrage Systems LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSArray (Random)
- (id)randomObject;
- (NSUInteger)randomIndex;
@end
//
// NSArray+Random.m
//
// Created by Jason Jones on 5/18/12.
// Copyright (c) 2012 Saxifrage Systems LLC. All rights reserved.
//
#import "NSArray+Random.h"
@implementation NSArray (Random)
- (id)randomObject {
return [self objectAtIndex:[self randomIndex]];
}
- (NSUInteger)randomIndex {
return arc4random() % [self count];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment