【问题标题】:How to remove value (not key) from NSmutableDictionary如何从 NSmutableDictionary 中删除值(不是键)
【发布时间】:2015-05-07 14:58:22
【问题描述】:

我有一个 NSmutableDictionary,我用它来填充 tableView。现在我想让我的 tableView 中的行可编辑。这是我的代码:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;

}

当一个人选择行时

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //Below four lines to get the name of course to delete

        NSString *key = [[self sectionKeys] objectAtIndex:[indexPath section]];//This is the key
        NSArray *contents = [[self sectionContents] objectForKey:key];
        NSString *contentForThisRow = [contents objectAtIndex:[indexPath row]];//This is the value

        [_sectionContents removeObjectForKey:key];//this can delete the key,not fit here, should delete value
         NSLog(@"Dictionary: %@", [_sectionContents description]);//test dictionary here
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

在这里,我的情况是一个键可能有多个值,所以当用户选择要删除的行时,上面的代码会删除整个键和其他值,这不是我想要的,也会产生错误。

所以我的问题是不使用removeObjectForKey,请问从字典中只删除值而不是键的正确方法是什么?

这是我在字典中填充的代码:

//New code for populating dictionary
    if ([_sectionContents objectForKey:AddKey] != nil) {
        //Already exist a value for the key
        id object = [_sectionContents objectForKey:AddKey];
        NSMutableArray *objectArray;
        //objectArray = [[NSMutableArray alloc] init];
        if ([object isKindOfClass:[NSMutableArray class]]) {//if object is a mutableArray already

            objectArray = (NSMutableArray *)object;
            //NSLog(@"1.The code runs through here!");
        } else {//If object is not array, it means that only one value exists here.

            //The following convert string to correct format
            NSString *oldCourse=nil;

            if ([object isKindOfClass:[NSString class]]) {
                oldCourse = object;
            } else if ([object respondsToSelector:@selector(stringValue)]) {
                oldCourse = [object stringValue];
            } else if ([object respondsToSelector:@selector(description)]) {
                oldCourse = [object description];
            }

           NSString *newString = [[oldCourse componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];//remove newline
            NSString * newString2 = [newString substringWithRange:NSMakeRange(7, [newString length]-7)];//cut the front
            //To erase the symbols
            NSString *newString3 = [newString2 stringByReplacingOccurrencesOfString:@")" withString:@""];
            NSString *newString4 = [newString3 stringByReplacingOccurrencesOfString:@"\"" withString:@""];

            //NSLog(@"%@",newString4);
            //if ([oldCourse isKindOfClass:[NSString class]])
            //NSLog(@"Become string here!");

            objectArray = [[NSMutableArray alloc] init];
            if(![objectArray containsObject:newString4])
                if(![_msgCourse containsObject:newString4])
             [objectArray insertObject:newString4 atIndex:0];
           // NSLog(@"2.The code runs through here!");
        //NSMutableArray *objectArray = [[NSMutableArray alloc] init];
        }
        NSLog(@"%@",objectArray);

        NSString *message;
        if([objectArray containsObject:course])//Giving out warning if course retaken
        {UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error: this course have been selected already." message:message delegate:nil cancelButtonTitle:@"Return to course planner" otherButtonTitles:nil, nil];

            [alert show];}

        if(![objectArray containsObject:course] && ![course isEqualToString:[objectArray objectAtIndex:0]] &&
           ![_msgCourse containsObject:course])
                   [objectArray addObject:course];

        if(![_msgCourse containsObject:course])//Use this flag to avoid retake class
            [_msgCourse addObject:course];

        //NSLog(@"3.The code runs through here!");

        [_sectionContents setObject:objectArray forKey:AddKey];
    } else {
        //No value for the key, add new value
        NSString *message;
        if([_msgCourse containsObject:course])//If course existed
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error: this course have been selected already." message:message delegate:nil cancelButtonTitle:@"Return to course planner" otherButtonTitles:nil, nil];

                [alert show];
        }

       if(![_msgCourse containsObject:course])
       {
           [_sectionContents setObject:[NSArray arrayWithObjects:course,nil] forKey:AddKey];
           [_msgCourse addObject:course];
       }

    }

【问题讨论】:

  • 一个键怎么可能有多个值?
  • @trojanfoe,他们已经实现了存储桶:NSArray *contents = [[self sectionContents] objectForKey:key];
  • @trojanfoe 可能值包含值数组。
  • 好的,所以问题是“如何从数组中删除一个值”。
  • 但是 OP 不知道要删除哪个值。模型坏了。

标签: ios uitableview nsmutabledictionary


【解决方案1】:

如果我理解正确,您试图从部分中删除元素,但实际上删除了整个部分。接下来你应该这样做:

NSString *key = [_sectionKeys objectAtIndex:[indexPath section]];//This is the key
NSMutableArray *contents = _sectionContents[key];
//Delete only selected row
[contents removeObjectAtIndex:indexPath.row]

这应该可行。

【讨论】:

  • 非常感谢您的回复,但是它给出了诸如“在'id'类型的对象上找不到mutableCopy”之类的错误,请问这是什么意思?
  • @user4441082 不要使用属性语法来调用方法。
  • @user4441082 更新了我的答案,正确创建了 NSMutableArray。
  • 您好,感谢您的更新。最后一行似乎有错误。说“'NSMutableArray' 没有可见的@interface 声明选择器“setObject:for Key:”
  • @user4441082 是的,对不起。更新了 sectionContents 而不是 sectionKeys
【解决方案2】:

由于您的键值对的值是数组:NSArray *contents = [[self sectionContents] objectForKey:key];,因此您真正需要知道的是如何从数组中删除元素。

这很简单:

//Need a mutable version. I've assumed it isn't already mutable. If it is, you can 
//adjust accordingly.

NSMutableArray *contents = [[self sectionContents][key] mutableCopy];
id object = /* You need to determine which element to remove */;
[contents removeObject:object];

//Put the modified array back into the dictionary
[self sectionContents][key] = contents;

【讨论】:

  • 好的,谢谢。我会密切关注它以防它被批准
  • 谢谢詹姆斯,你的方法很容易理解,但它在“mutableCopy”上给出错误,说“mutableCopy not found on object of type 'id'”,请问这是什么意思?跨度>
  • 这意味着我犯了一点错误;)我没有使用IDE,而是从内存中编写的。给我 2 分钟修复它
  • 我不知道这意味着什么...我可以在我刚刚写的一个小测试中通过id 调用mutableCopy
  • @user4441082,您的字典是否包含only 数组?是编译时的错误还是运行时的错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
相关资源
最近更新 更多