NSMutableDictionary类

作者:追风剑情 发布于:2019-3-2 10:47 分类:Objective-C

NSMutableDictionary是可变词典。
NSMutableDictionary是NSDictionary的子类。

常用的NSMutableDictionary方法
方法 描述
+(instancetype) dictionaryWithCapacity: size 使用一个初始指定的size创建可变词典
-(instancetype) initWithCapacity: size 将新分配的词典初始化为指定的size
-(void) removeAllObjects     删除词典中所有记录
-(void) removeObjectForKey: key 删除词典中指定key对应的记录
-(void) setObject: obj forKey: key 向词典为key的键添加obj,如果key已存在,则替换该值

说明:
表中的key、key1、key2、obj、obj1和obj2是任意对象,size是一个NSUInteger无符号整数。

示例

  1. #import <Foundation/Foundation.h>
  2.  
  3. int main(int argc, const char * argv[]) {
  4. @autoreleasepool {
  5. // 创建一个空的可变词典, 注意:key不能为nil
  6. NSMutableDictionary *glossary = [NSMutableDictionary dictionary];
  7. // 存储3个条目在类别中
  8. /*
  9. [glossary setObject: @"A class defined so other classes can inherit from it"
  10. forKey: @"abstract class"];
  11. [glossary setObject: @"To implement all the methods defined in a protocol"
  12. forKey: @"adopt"];
  13. [glossary setObject: @"Storing an object for later use"
  14. forKey: @"archiving"];
  15. */
  16. // 与上面的语法等价
  17. glossary[@"abstract class"] = @"A class defined so other classes can inherit from it";
  18. glossary[@"adopt"] = @"To implement all the methods defined in a protocol";
  19. glossary[@"archiving"] = @"Storing an object for later use";
  20. // 检索并显示它们
  21. /*
  22. NSLog(@"abstract class: %@", [glossary objectForKey: @"abstract class"]);
  23. NSLog(@"adopt: %@", [glossary objectForKey: @"adopt"]);
  24. NSLog(@"archiving: %@", [glossary objectForKey: @"archiving"]);
  25. */
  26. // 与上面的语法等价
  27. NSLog(@"abstract class: %@", glossary[@"abstract class"]);
  28. NSLog(@"adopt: %@", glossary[@"adopt"]);
  29. NSLog(@"archiving: %@", glossary[@"archiving"]);
  30. }
  31. return 0;
  32. }

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号