Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I shuffle an NSArray?
    text
    copied!<p>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?</p> <p>Anything in objective-c similar to Collections.shuffle() (Java)?</p> <h2>Edit</h2> <pre><code>static NSUInteger random_below(NSUInteger n) { NSUInteger m = 1; do { m &lt;&lt;= 1; } while(m &lt; n); NSUInteger ret; do { ret = random() % m; } while(ret &gt;= 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:&amp;myError]; if (theResults == nil) { NSLog(@"Testing: No results found"); }else { NSLog(@"Testing: Results found."); } [request release]; [sortDescriptors release]; for(NSUInteger i = [theResults count]; i &gt; 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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload