我有这段代码:
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 但由于缺少索引而无法正常工作。
我需要做些什么来按照我想要的方式工作?
答案 0 :(得分:2)
如果您知道最大可能值,则可以使用[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"];
答案 1 :(得分:1)
改为使用NSMutableDictionary
。
customServicesDictionary[@(indexSelected)] = textField.text;