insertObject: atIndex: - index 3 beyond bounds for empty array

谁说我不能喝 提交于 2019-12-01 00:57:40

The capacity is merely how many objects a container class can hold. Inserting at an index requires that index to be a valid placement for the new object based on the total number of objects contained in the container (not the total number of objects that CAN be contained).

If your array's values are index dependent (which is seems like perhaps a different architecture or data structure would be better) then you can ensure that every index is filled by prepopulating the array with NSNulls. This would require you to check for NSNulls when reading from the array later on though which would likely be extra work, hence why this is probably not the best approach. In any case, you can change your code to the following to fix your crash.

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];
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!