2012-10-25 58 views
2

我創建基於陣列的字典關鍵的:insertObject:atIndex: - 指數3超出界限爲空數組

factsBuiltArray = [NSMutableArray arrayWithCapacity: 6]; 
if ([statusDict count] == 10) { 
    for (NSString *key in [statusDict allKeys]) { 
     if ([key isEqualToString: @"currenciesAndConversions"]) { 
      [factsBuiltArray insertObject:key atIndex: 0]; 
     } 
     else if ([key isEqualToString: @"languageAndTranslations"]) { 
      [factsBuiltArray insertObject:key atIndex: 1]; 
     } 
     else if ([key isEqualToString: @"plugSize"]) { 
      [factsBuiltArray insertObject:key atIndex: 2]; 
     } 
     else if ([key isEqualToString: @"timezone"]) { 
      [factsBuiltArray insertObject:key atIndex: 3]; // crashes over here 
     } 
     else if ([key isEqualToString: @"population"]) { 
      [factsBuiltArray insertObject:key atIndex: 4]; 
     } 
     else if ([key isEqualToString: @"wikipedia"]) { 
      [factsBuiltArray insertObject:key atIndex: 5]; 
     } 
    } 
} 

崩潰日誌是:

*** -[__NSArrayM insertObject:atIndex:]: index 3 beyond bounds for empty array 

爲什麼插入對象一個容量爲6的數組使其崩潰?很混亂!

回答

10

容量僅僅是容器類可容納多少個對象。在索引處插入要求索引是基於容器中包含的對象總數(而不是可包含的對象總數)爲新對象的有效位置。

如果你的數組的值是索引相關的(這看起來可能是一個不同的架構或數據結構會更好),那麼你可以通過預先填充NSNulls來確保每個索引都被填充。這將需要你在稍後從數組讀取時檢查NSNulls,儘管這可能是額外的工作,因此這可能不是最好的方法。無論如何,您可以將您的代碼更改爲以下內容以解決您的崩潰問題。

factsBuiltArray = [NSMutableArray arrayWithCapacity: 6]; 

for (NSUInter i = 0; i < 6; i++) { 
    [factsBuiltArray addObject:[NSNull null]]; 
} 

if ([statusDict count] == 10) { 

    for (NSString *key in [statusDict allKeys]) { 

     if ([key isEqualToString: @"currenciesAndConversions"]) { 

      [factsBuiltArray replaceObjectAtIndex:0 withObject:key]; 
     } 
     else if ([key isEqualToString: @"languageAndTranslations"]) { 

      [factsBuiltArray replaceObjectAtIndex:1 withObject:key]; 
     } 
     else if ([key isEqualToString: @"plugSize"]) { 

      [factsBuiltArray replaceObjectAtIndex:2 withObject:key]; 
     } 
     else if ([key isEqualToString: @"timezone"]) { 

     [factsBuiltArray replaceObjectAtIndex:3 withObject:key]; 

     } 
     else if ([key isEqualToString: @"population"]) { 

      [factsBuiltArray replaceObjectAtIndex:4 withObject:key]; 
     } 
     else if ([key isEqualToString: @"wikipedia"]) { 

      [factsBuiltArray replaceObjectAtIndex:5 withObject:key]; 
     } 
    } 
} 
+1

容量NSArrays甚至不是。這只是內存分配的一個提示;該陣列可能會比您傳遞的容量更大(與CFArrays不同)。 – Wevah

+0

好點,NSArray在達到容量時重新分配。感謝您指出@Wevah – NSProgrammer