All examples I find on shuffling arrays are for NSMutableArrays. Copying an NSArray to an NSMutable array, shuffling, then copying back always crashes the application. Is it even possible to shuffle an NSArray?
Anything in objective-c similar to Collections.shuffle() (Java)?
Edit
static NSUInteger random_below(NSUInteger n) {
NSUInteger m = 1;
do {
m <<= 1;
} while(m < n);
NSUInteger ret;
do {
ret = random() % m;
} while(ret >= n);
return ret;
}
- (NSArray *)loadAllData{
XYZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quote" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[request setEntity: entity];
NSError *myError;
NSArray *theResults = [managedObjectContext executeFetchRequest:request error:&myError];
if (theResults == nil) {
NSLog(@"Testing: No results found");
}else {
NSLog(@"Testing: Results found.");
}
[request release];
[sortDescriptors release];
for(NSUInteger i = [theResults count]; i > 1; i--) {
NSUInteger j = random_below(i);
[theResults exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
}
return theResults;
}
warning: 'NSArray' may not respond to '-exchangeObjectAtIndex:withObjectAtIndex:' which crashed the application.
error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_PFArray exchangeObjectAtIndex:withObjectAtIndex:]: unrecognized selector sent to instance 0x3d35a40