当我在 IOS 中删除 NSMutableArray 时,我的 NSMutableDictionary 删除了对象?

My NSMutableDictionary removes object When i delete NSMutableArray in IOS?

contactSectionDict = [[NSMutableDictionary alloc] init];
contactsForSection = [[NSMutableArray alloc] init];
contactsIndexTitles = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H",@"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z",@"#"];

for(int i=0;i<contactsIndexTitles.count;i++)
{
    for(int j=0;j<names.count;j++)
    {
        NSArray * splitArray = [[names objectAtIndex:j] componentsSeparatedByString:@" "];
        if ([[splitArray objectAtIndex:0] hasPrefix:[contactsIndexTitles objectAtIndex:i]]) {
            //[contactSectionDict setValue:[names objectAtIndex:j] forKey:[contactsIndexTitles objectAtIndex:i]];
            [contactsForSection addObject:[names objectAtIndex:j]];
        }
    }
    [contactSectionDict setValue:contactsForSection forKey:[contactsIndexTitles objectAtIndex:i]];
    [contactsForSection removeAllObjects];
}

在第一次迭代中,它在 contactsForSection 中存储了 36 个对象,并将其存储在 contactsectionDict 中用于 Key"A" 然后我想为索引 B 存储联系人,为此我从 contactsForSection 中删除了对象,但它也删除了字典中键 "A" 的值也是。 当字典将针对所有索引进行设置时,我会将其提供给 table 视图以像 Apple Contact Application 一样显示它们。 请建议我更好的方法。

您需要为每个字母创建一个新的 contactsForSection 数组:

contactSectionDict = [[NSMutableDictionary alloc] init];
contactsIndexTitles = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H",@"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z",@"#"];

for(int i=0;i<contactsIndexTitles.count;i++)
{
    contactsForSection = [[NSMutableArray alloc] init];
    for(int j=0;j<names.count;j++)
    {
        NSArray * splitArray = [[names objectAtIndex:j] componentsSeparatedByString:@" "];
        if ([[splitArray objectAtIndex:0] hasPrefix:[contactsIndexTitles objectAtIndex:i]]) {
            //[contactSectionDict setValue:[names objectAtIndex:j] forKey:[contactsIndexTitles objectAtIndex:i]];
            [contactsForSection addObject:[names objectAtIndex:j]];
        }
    }
    [contactSectionDict setValue:contactsForSection forKey:[contactsIndexTitles objectAtIndex:i]];
    [contactsForSection removeAllObjects];
}