字典也和数组,字符串一样也有一个可变的子类, 只是涉及的方法名不一样, 但是原理都差不多.
涉及到的方法:
removeObjectForKey: 删除指定的键值对(PS: 这里输入的只能是键, 输入键会删掉键和值, 但是输入值是不会发生任何事情的).
下面我们来看看例子:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableDictionary *dicti = [NSMutableDictionary new]; [dicti setObject:@"Five" forKey:@"5"]; [dicti setObject:@"Four" forKey:@"4"]; //添加指定的键值对 // [dicti setObject:@"Five" forKey:@"5"]; //添加键值对和删除键值对的时候没有说是插入到哪里, 和删除哪一个, 因为字典中的键值对是不讲究位置的. NSLog(@"dicti = %@", dicti); //removeObjectForKey:删除对应的键值对. //删除键值对也是同样不将就顺序. // [dicti removeObjectForKey:@"4"]; [dicti removeObjectForKey:@"5"]; NSLog(@"diciti = %@", dicti); [dicti release]; } return 0; }
输出来的结果:
2014-10-13 21:16:31.843 NSMutableDictionary[6749:303] dicti = { 4 = Four; 5 = Five; } 2014-10-13 21:16:31.844 NSMutableDictionary[6749:303] diciti = { 4 = Four; } Program ended with exit code: 0