开发者

How can I shuffle an NSArray?

All examples I find on shuffling arrays are for NSMutableArrays. Copying an NSArray to an NSMutable array, shuffling, then copying back always crashes the appl开发者_运维百科ication. 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


OK. I think I see a problem. Always look at the error message. I thought you said that you were using NSMutableArrays in this function?

NSArray *theResults = [managedObjectContext executeFetchRequest:request error:&myError];

Change that to

NSMutableArray *theResults = [[managedObjectContext executeFetchRequest:request error:&myError] mutableCopy];

Tell me if it works, and if it doesn't, I'll try and help.

Some more info:

-exchangeObjectAtIndex:withObjectAtIndex:

is a method for a NSMutableArray. You were using a NSArray, they're different classes (NSMutableArray is a subclass (and adds methods that mean you can modify it) of NSArray).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜