需要在 NSMutableArray 的特定索引处添加文本字段内容

Posted

技术标签:

【中文标题】需要在 NSMutableArray 的特定索引处添加文本字段内容【英文标题】:Need to add text field contents at specific index of NSMutableArray 【发布时间】:2016-03-29 15:53:24 【问题描述】:

我有这个代码:

        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];

我需要在 customServicesArray 的特定索引处添加元素;显然,如果数组为空,我所拥有的将不起作用。我已经尝试过 addObject 但由于缺少索引,这也不起作用。

我必须做些什么才能使这项工作按我想要的方式工作?

【问题讨论】:

Is Cocoa's NSMutableArray sparse? 【参考方案1】:

如果您知道最大可能值,您可以使用 [NSNull null] 或其他一些虚拟对象预填充您的数组。

或者添加一些类似的代码

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"];

【讨论】:

【参考方案2】:

请改用NSMutableDictionary

customServicesDictionary[@(indexSelected)] = textField.text;

【讨论】:

这是我唯一的选择吗?有很多代码依赖于 customServicesArray 作为 NSMutableArray...

以上是关于需要在 NSMutableArray 的特定索引处添加文本字段内容的主要内容,如果未能解决你的问题,请参考以下文章

通过 AFNetworking 在指定索引处将 UIImage 添加到 NSMutableArray

如何在 NSMutableArray 中选择特定索引并存储在 nsarray [关闭]

如何在 NSArray 的第一个索引处添加对象

需要在特定索引处重叠数组的子数组

Java ArrayList 在特定索引处替换

每次需要访问特定索引处的元素时是不是可以重新排序数组?