首页 > 代码库 > NSDictionary的使用

NSDictionary的使用

通过唯一的key找到对应的value,类似于Java中的Map

创建NSDictionary的方法

  • + (id)dictionary
  • + (id)dictionaryWithObject:(id)object forKey:(id<NSCopying>)key //作为key的对象需实现NSCopying协议
  • + (id)dictionaryWithObjectsAndKeys:(id)firstObject,... //key和Object需成功出  , 如: NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"v1", @"k1",@"v2",@"k2",nil]
  • + (id)dictionaryWithDictionary:(NSDictionary *)dict
  • + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
  • - (id)initWithObjectsAndKeys:(id)firstObject,...
  • - (id)initWithDictionary:(NSDictionary *)otherDictionary
  • - (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
  • + (id)dictionaryWithContentsOfFile:(NSString *)path
  • + (id)dictionaryWithContentsOfURL:(NSURL *)url
  • - (id)initWithContentsOfFile:(NSString *)path
  • - (id)initWithContentsOfURL:(NSURL *)url

NSDictionary常用方法

  • - (NSUInteger) count   //返回字典的key数
  • - (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary   //比较两个字典
  • - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile //将一个NSDictionary持久化到文件中去

NSDictionary访问key和value

  • - (NSArray *)allKeys   //返回所有的key
  • - (NSArray *)allKeysForObject:(id)anObject  //返回anObject元素对应的所有key
  • - (NSArray *)allValues   //返回所有的value
  • - (id)objectForKey:(id)aKey  //根据aKey返回对应的value
  • - (NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)marker //返回keys对应的所有value, 如果没有对应的value, 用marker代替

NSDictionary遍历

  • 快速遍历: for (NSString *key in dict)
  • 迭代器遍历:
    • - (NSEnumerator *)keyEnumerator  //key的迭代器
    • - (NSEnumerator *)objectEnumerator  //value的迭代器
  • block遍历 [dict enumeratorKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop){  NSLog(@"key=%@, object=%@", key, object); }];

NSDictionary的key排序

  • - (NSArray *)keyssortedByValueUsingComparator:(NSComparator)cmptr
  • - (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr
  • - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator