2013-12-21 27 views
0

我從1-4存儲一個NSMutableArray內4個獨特的數字。我已經通過使用此代碼來完成此操作:的NSMutableArray內的setTitle

storeArray = [[NSMutableArray alloc] init]; 
    BOOL record = NO; 
    int x; 

    for (int i=1; [storeArray count] < 4; i++) //Loop for generate different random values 
    { 
     x = arc4random() % 4;//generating random number 
     if(i==1)//for first time 
     { 
      [storeArray addObject:[NSNumber numberWithInt:x]]; 
     } 
     else 
     { 
      for (int j=0; j<= [storeArray count]-1; j++) 
      { 
       if (x ==[[storeArray objectAtIndex:j] intValue]) 
        record = YES; 
      } 

      if (record == YES) 
      { 
       record = NO; 
      } 
      else 
      { 
       [storeArray addObject:[NSNumber numberWithInt:x]]; 
      } 
     } 
    } 

然後,我可以使用storeArray [1]等打印出數字。

的問題是,我想打印這裏面的數字。

[option1 setTitle:questions[r][storeArray[0]] forState: UIControlStateNormal]; 
[option2 setTitle:questions[r][storeArray[1]] forState: UIControlStateNormal]; 
[option3 setTitle:questions[r][storeArray[2]] forState: UIControlStateNormal]; 
[option4 setTitle:questions[r][storeArray[3]] forState: UIControlStateNormal]; 

我該怎麼做?,導致我當我這樣做,我得到線程sigbrt錯誤?

+0

數組索引從零開始,而不是一個索引。如果數組中有四個元素,則可以通過storeArray [3]'使用'storeArray [0]'來訪問它們。 – godel9

+0

如何聲明'questions'變量?如果您發佈SIGABRT的堆棧跟蹤將會很有幫助。 – highlycaffeinated

回答

0

的問題是,你的算法是錯誤的,當有衝突,因爲你試圖保持數字獨一無二的,你不記錄任何東西讓你的陣列可能並不總是期望的長度。事實上,這種情況在您的案例中有91%的機會發生,所以它看起來總是在發生。

,而不是試圖編寫自己的算法,只需使用現有的類。只需使用NSSet來保證陣列中數字的唯一性。

NSMutableSet *set = [[NSMutableSet alloc] init]; 
while(set.count < 4) { 
    int x = arc4random() % 4; 
    [set addObject:[NSNumber numberWithInteger:x]]; 
} 

NSArray * storeArray = [set allObjects];