NSDictionary类

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

NSDictionary是不可变词典。

常用的NSDictionary方法
方法 描述
+(instancetype) dictionaryWithObjectsAndKeys: obj1,key1,obj2,key2,...,nil 使用键-对象对{key1,obj1}、{key2,obj2}、...创建词典
-(instancetype) initWithObjectsAndKeys: obj1,key1,obj2,key2,...,nil 将新分配的词典初始化为键-对象对{key1,obj1}、{key2,obj2}
-(NSArray *) allKeys 返回一个数组包含词典中所有的键
-(NSUInteger) count 返回词典中的记录数
-(NSEnumerator *) keyEnumerator 为词典中所有的键返回一个NSEnumerator对象
-(NSArray *) keysSortedByValueUsingSelector: (SEL) selector 返回词典中的键数组,它根据selector指定的比较方法进行排序
-(NSEnumerator *) objectEnumerator 为词典中的所有值返回一个Enumerator对象
-(id) objectForKey: key 返回指定的key对象
-(void) enumerateKeysAndObjectsUsingBlock: (void(^)(id key, id obj, BOOL *stop)) block 通过块获取词典中的每一个条目,条目包括键-对象对,只有当所有的元素都遍历完成或设置变量指针stop为YES才处理结束

示例

  1. #import <Foundation/Foundation.h>
  2.  
  3. int main(int argc, const char * argv[]) {
  4. @autoreleasepool {
  5. /*
  6. NSDictionary *glossary =
  7. [NSDictionary dictionaryWithObjectsAndKeys:
  8. @"A class defined so other classes can inherit from it",
  9. @"abstract class",
  10. @"To implement all the methods defined in a protocol",
  11. @"adopt"
  12. @"Storing an object for later use"
  13. @"archiving",
  14. nil]; //必须以nil结尾
  15. */
  16. // 与上面的语法等价
  17. NSDictionary *glossary = @{
  18. @"abstract class": @"A class defined so other classes can inherit from it",
  19. @"adopt": @"To implement all the methods defined in a protocol",
  20. @"archiving": @"Storing an object for later use"
  21. };
  22. // 打印词典中所有的键-值对
  23. for (NSString *key in glossary)
  24. NSLog(@"%@: %@", key, [glossary objectForKey: key]);
  25. NSLog(@"---------------------------------------------------");
  26. // 对key按字母排序后再打印
  27. NSArray *keys = [glossary allKeys];
  28. keys = [keys sortedArrayUsingComparator: ^(id obj1, id obj2) {
  29. return [obj1 compare: obj2];
  30. }];
  31. for (NSString *key in keys)
  32. NSLog(@"%@: %@", key, [glossary objectForKey: key]);
  33. }
  34. return 0;
  35. }

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号