Created
July 10, 2012 23:52
-
-
Save jasonwjones/3087021 to your computer and use it in GitHub Desktop.
NSArray category for getting a random index or object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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