iOS - 在 NSMutableArray 中打乱/随机化对象的顺序

标签 ios objective-c

我想在执行方法 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/

相关文章:

objective-c - 如何将 UIView 放在键盘上方

ios - Swift 中的开关 - 开关中的 Case 标签应该至少有一个可执行语句

ios - 使用枚举在 Sprite Kit 中组织 zPosition 值

objective-c - 从 Safari 显示 : Do you want to allow this page to open "(null)"? 启动的应用程序

ios - UIAlertController 背景色 iOS10

ios - 如何使用 MonoTouch 在 iOS 中的 post 请求中发送表单数据?

ios - RestKit 请求因 HTTP 错误而挂起

objective-c - Cocos2d 与 UIPinchGestureRecognizer

ios - 从 UIView 发送按钮点击值到它的 super View 的 super View (UIViewController)-iOS

ios - 如何在自定义 UIView 中从一个 View Controller 返回到另一个 View Controller ?