2015-05-07 1 views
1

У меня есть NSmutableDictionary, который я использую для заполнения таблицыView. Теперь я хочу сделать строки в моем tableView доступными для редактирования. Вот мой код:Как удалить значение (не ключ) из NSmutableDictionary

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

    } 
+1

Как ключ может иметь более одного значения? – trojanfoe

+0

@trojanfoe, они внедрили ведра: 'NSArray * contents = [[self sectionContents] objectForKey: key];' –

+0

@trojanfoe Может быть значение содержит массив значений. –

ответ

2

Если я правильно понял, вы пытаетесь удалить элемент из раздела, но на самом деле удаляемые весь раздел. Вам следует сделать следующее:

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

Это должно сработать.

+0

Большое спасибо за ваш ответ, но он выдает ошибку, например: «mutableCopy не найден на объекте типа« id », что это значит, пожалуйста? – user4441082

+0

@ user4441082 Не используйте синтаксис свойств для вызова методов. – rmaddy

+0

@ user4441082 обновил мой ответ, создав NSMutableArray правильно. – 4esterUA

3

Поскольку значения ваших пар ключ-значение являются массивами: 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; 
+0

Извините, я отредактировал неправильный ответ, должен был изменить свой собственный. – 4esterUA

+0

Хорошо спасибо. Я буду следить за ним, если он одобрен –

+0

Спасибо Джеймсу, ваш метод легко понять, но он выдает ошибку на «mutableCopy», говоря: «mutableCopy не найден на объекте типа« id », что это значит значит, пожалуйста? – user4441082