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

时间:2015-08-08 09:51:17

标签: ios contacts

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

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

1 个答案:

答案 0 :(得分:1)

您需要为每个字母创建一个新的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];
}