我想在执行方法 reloadData 时打乱/随机化我的 NSMutableArray 中项目的顺序。我尝试了以下操作,但控制台不断向我抛出以下错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI exchangeObjectAtIndex:withObjectAtIndex:]: unrecognized selector sent to instance 0x1748b2c60'
知道为什么会这样吗?我很难过。
ViewController.h
@property (strong, retain) NSMutableArray *neighbourData;
ViewController.m
- (void)reloadData:(id)sender
{
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:@"u000" forKey:@"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.neighbourData = (NSMutableArray *)responseObject;
[self.tableView reloadData];
NSUInteger count = [self.neighbourData count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[self.neighbourData exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSLog(@"This is the neighbourdata %@",self.neighbourData);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", [error localizedDescription]);
}];
最佳答案
错误表明 responseObject
实际上是一个不可变的 NSArray
。您应用的强制转换仅存在于编译器中,但实际上并没有在运行时更改任何内容。
改变:
self.neighbourData = (NSMutableArray *)responseObject;
到:
self.neighbourData = [(NSArray *)responseObject mutableCopy];
关于iOS - 在 NSMutableArray 中打乱/随机化对象的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42288500/