我在洗牌数组中找到的所有示例都是针对NSMutableArrays的。将NSArray复制到NSMutable数组,混洗,然后复制总是会使应用程序崩溃。是否有可能改组NSArray?
Objective-c中的任何内容类似于Collections.shuffle()(Java)?
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
答案 0 :(得分:2)
行。我想我看到了一个问题。始终查看错误消息。我以为你说你在这个函数中使用了NSMutableArrays?
NSArray *theResults = [managedObjectContext executeFetchRequest:request error:&myError];
将其更改为
NSMutableArray *theResults = [[managedObjectContext executeFetchRequest:request error:&myError] mutableCopy];
告诉我它是否有效,如果没有,我会尽力帮助。
更多信息:
-exchangeObjectAtIndex:withObjectAtIndex:
是NSMutableArray的方法。您使用的是NSArray,它们是不同的类(NSMutableArray是NSArray的子类(并添加了可以修改它的方法))。