2017-02-17 102 views
0

當方法reloadData執行時,我想隨機/隨機化NSMutableArray中的項目順序。我試了下面,但控制檯不斷拋出以下錯誤:iOS - 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]); 
      }]; 

回答

2

該錯誤指示responseObject實際上是一個不可變NSArray。您應用的強制轉換簡直在於編譯器,但它在運行時實際上不會改變任何內容。

變化:

self.neighbourData = (NSMutableArray *)responseObject; 

到:

self.neighbourData = [(NSArray *)responseObject mutableCopy]; 
+0

對於OP,這是一個重要的學習點。將變量轉換爲其他類型不會更改基礎對象的類型。它只是迫使編譯器*認爲它是一種不同的類型。如果對象是**不是**可變數組,則需要一個將不可變數組作爲參數的函數('mutableCopy'),並將您帶回包含相同對象的新可變數組。 –

0

對於生產,你真的應該使用內置的Fisher-Yates shuffle in Gamekit。如果你這樣做了傾斜的目的,那麼問題是在該行:

int n = (arc4random() % nElements) + i; 

您正在從第一隨機數到最後一個元素,然後要添加我給它。顯然這意味着你的索引現在可以超出範圍。擺脫+我

+0

此答案不會嘗試解決問題中提出的問題。 – rmaddy

+0

這是一個有效的觀點,但正如rmaddy所說的那樣,這不是對問題的回答。 –

0

self.neighbourData = (NSMutableArray *)responseObject; 你必須確保你的responseObject是NSMutableArray的一個實例。即使你將類型responseObject轉換爲NSMutableArray,如果它不是NSMutableArray的實例,它會崩潰,因爲它沒有exchangeObjectAtIndex:withObjectAtIndex :.在這種情況下,您的responseObject是一個NSArray實例,您可以將代碼更改爲: NSArray *tmp = (NSArray *)responseObject; self.neighbourData = [tmp mutableCopy]; 我認爲這適用於您。