0

I have this code:

        NSMutableArray *customServicesArray = [[NSMutableArray alloc] initWithCapacity: 24];
    PreferenceData *userPreferences = [PreferenceData MR_findFirstInContext: [NSManagedObjectContext MR_defaultContext]];

    //  fill the array with existing data (if any)
    customServicesArray = [NSMutableArray arrayWithObjects: userPreferences.aCustomServices1, userPreferences.aCustomServices2, userPreferences.aCustomServices3, userPreferences.aCustomServices4, userPreferences.aCustomServices5, userPreferences.aCustomServices6, userPreferences.aCustomServices7, userPreferences.aCustomServices8, userPreferences.aCustomServices9, userPreferences.aCustomServices10, userPreferences.aCustomServices11, userPreferences.aCustomServices12, userPreferences.aCustomServices13, userPreferences.aCustomServices14, userPreferences.aCustomServices15, userPreferences.aCustomServices16, userPreferences.aCustomServices17, userPreferences.aCustomServices18, userPreferences.aCustomServices19, userPreferences.aCustomServices20, userPreferences.aCustomServices21, userPreferences.aCustomServices22, userPreferences.aCustomServices23, userPreferences.aCustomServices24,nil];

    NSInteger indexSelected = [oCustomServicesPickerView selectedRowInComponent:0];
    if(customServicesArray.count > (unsigned long)indexSelected)
        [customServicesArray replaceObjectAtIndex:indexSelected withObject:textField.text];  //  check to see max number of objects; might want to insert object then
    else
        [customServicesArray insertObject:textField.text atIndex: indexSelected];

I need to add elements to the customServicesArray at a specific index; obviously what I have isn't working if the array is empty. I have tried addObject but that doesn't work either due to lack of index.

What do I have to do to make this work the way I want it to?

SpokaneDude
  • 4,856
  • 13
  • 64
  • 120

2 Answers2

2

You can prefill your array with [NSNull null] or some other dummy objects if you know maximum possible values.

Or add some code like that

NSInteger indexSelected = [oCustomServicesPickerView selectedRowInComponent:0];

while (customServicesArray.count <= indexSelected) {
    [customServicesArray addObject:[NSNull null]]; // Here you can add some dummy object
}

[customServicesArray replaceObjectAtIndex:indexSelected withObject: @"textFieldText"];
Peter K
  • 438
  • 3
  • 10
1

Use NSMutableDictionary instead.

customServicesDictionary[@(indexSelected)] = textField.text;
Cy-4AH
  • 4,370
  • 2
  • 15
  • 22