If you want to do this several times from different places in your code, think about it: "Objective C way" is to create a category in NSMutableArray that adds the randomObjects method. The method itself should generate three random numbers from 0 to the length of the array -1 ( N-1 ), and then return a set of objects from the array at these indices in accordance with the other answers here (in particular, dasblinkenlight).
First create a category. Create a new NSMutableArray+RandomObject.h header file containing:
@interface NSMutableArray (RandomObjects) - (NSSet *) randomObjects; @end
<parentheses RandomElement is the name of your category. Any class you write that includes this new header file will provide all your NSMutableArray instances with the RandomElement method.
Then implementation in NSMutableArray+RandomObjects.m :
@implementation NSMutableArray (RandomObjects) - (NSSet *) randomObjects { // Use the code from @dasblinkenlight answer here, adding the following line: return picks; } @end
And thatβs basically it. You have effectively added this feature to NSMutableArray .
source share