[iOS]NSHashTable和NSMapTable用法


一个项目中的需求


在iOS项目开发过程中,我们经常会使用到NSSetNSArrayNSDictionary三个类,它们为我们设计较友好的数据结构时提供了很方便的方法

先准备本文中将要使用的对象:

#import <Foundation/Foundation.h>

@interface HHHuman : NSObject

@property (nonatomic ,strong) NSString *name;

+ (instancetype) humanWithName:(NSString *)n;

@end

@implementation HHHuman

+ (instancetype) humanWithName:(NSString *)n
{
    HHHuman *human = [[HHHuman alloc] init];
    human.name = n;
    
    return [human autorelease];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s retainCount is %lu",self.name,[self retainCount]];
}
- (void)dealloc
{
    self.name = nil;
    [super dealloc];
}
@end

在程序开发过程中,经常会用到诸如此类的Model对象.
用法呢也大致会有如下几种方式:
1.通过有序的数列进行存储,数组NSArray;

    HHHuman *human_1 = [HHHuman humanWithName:@"lilei"];
    HHHuman *human_2 = [HHHuman humanWithName:@"hanmeimei"];
    HHHuman *human_3 = [HHHuman humanWithName:@"lewis"];
    HHHuman *human_4 = [HHHuman humanWithName:@"xiaohao"];
    HHHuman *human_5 = [HHHuman humanWithName:@"beijing"];

    id list = @[human_1,human_2,human_3,human_4,human_5];
    NSLog(@"%@",list);

输出的结果如下:

(
    "lilei's retainCount is 2",
    "hanmeimei's retainCount is 2",
    "lewis's retainCount is 2",
    "xiaohao's retainCount is 2",
    "beijing's retainCount is 2"
)

2.通过统一的关键字进行存储,字典NSDictionary;

    HHHuman *human_1 = [HHHuman humanWithName:@"lilei"];
    HHHuman *human_2 = [HHHuman humanWithName:@"hanmeimei"];
    HHHuman *human_3 = [HHHuman humanWithName:@"lewis"];
    HHHuman *human_4 = [HHHuman humanWithName:@"xiaohao"];
    HHHuman *human_5 = [HHHuman humanWithName:@"beijing"];
    id dic = @{@"excellent":human_1};
    //同样在控制台输出上文字典,用来查看每个对象的保留值
    NSLog(@"%@",list);

输出的结果如下:

(
    "lilei's retainCount is 3",
    "hanmeimei's retainCount is 3",
    "lewis's retainCount is 2",
    "xiaohao's retainCount is 2",
    "beijing's retainCount is 2"
)

通过上述两个例子我们能够发现一个问题,即将对象添加到容器时,会对该对象的引用技术+1
这样就会有可能发生循环持有的问题,例如如下代码:

@interface HHHuman : NSObject

@property (nonatomic ,strong) NSString *name;
@property (nonatomic ,strong) NSMutableArray *family;

+ (instancetype) humanWithName:(NSString *)n;

@end

@implementation HHHuman

+ (instancetype) humanWithName:(NSString *)n
{
    HHHuman *human = [[HHHuman alloc] init];
    human.name = n;
    human.family = [[NSMutableArray alloc] init];
    [human.family addObject:human];

    return [human autorelease];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s retainCount is %lu",self.name,[self retainCount]];
}
- (void)dealloc
{
    self.name = nil;
    self.family = nil;
    [super dealloc];
}

@end

在以上代码中,一个human的实例对象中包含一个strong修饰的family属性,但是在family属性中,又添加了human自身对象,这样会造成循环持有的问题,而导致内存泄漏。
但是项目需求又要求我们在该Model对象中完成如此代码,我们不得已会多创建一个类HHHumanRelationShip,如下所示:

#import <Foundation/Foundation.h>



@interface HHHuman : NSObject

@property (nonatomic ,strong) NSString *name;

+ (instancetype) humanWithName:(NSString *)n;

@end

@implementation HHHuman

+ (instancetype) humanWithName:(NSString *)n
{
    HHHuman *human = [[HHHuman alloc] init];
    human.name = n;

    return [human autorelease];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s retainCount is %lu",self.name,[self retainCount]];
}
- (void)dealloc
{
    self.name = nil;
    [super dealloc];
}

@end

@interface HHHumanRelationShip : NSObject

@property (nonatomic ,strong) HHHuman *human;
@property (nonatomic ,strong) NSArray *family;

+ (instancetype)relationShipWithHuman:(HHHuman *)human family:(NSArray *)members;

@end

@implementation HHHumanRelationShip

+ (instancetype)relationShipWithHuman:(HHHuman *)human family:(NSArray *)members
{
    HHHumanRelationShip *rs = [[HHHumanRelationShip alloc] init];
    rs.human = human;
    rs.family = members;
    
    return [rs autorelease];
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s family's member is %@",self.human,self.family];
}
- (void)dealloc
{
    self.human = nil;
    self.family = nil;
    [super dealloc];
}

@end

int main(int argc, const char * argv[])
{
    
    HHHuman *human_0 = [HHHuman humanWithName:@"parent"];
    HHHuman *human_1 = [HHHuman humanWithName:@"lilei"];
    HHHuman *human_2 = [HHHuman humanWithName:@"hanmeimei"];
    HHHuman *human_3 = [HHHuman humanWithName:@"lewis"];
    HHHuman *human_4 = [HHHuman humanWithName:@"xiaohao"];
    HHHuman *human_5 = [HHHuman humanWithName:@"beijing"];
    

    id list = @[human_1,human_2,human_3,human_4,human_5];
    

    HHHumanRelationShip *relationShip = [HHHumanRelationShip relationShipWithHuman:human_0 family:list];
    NSLog(@"%@",relationShip);
    
    return 0;
}


NSHashTable


很明显,大家能够看到这样造成了程序代码的臃肿
根据上述需求和功能,在iOS6之后,Objective-C Foundation框架中添加了两个类分别是NSHashTableNSMapTable

  • NSHashTable
    • 构造函数
      • - (instancetype)initWithOptions:(NSPointerFunctionsOptions)options capacity:(NSUInteger)initialCapacity
      • - (instancetype)initWithPointerFunctions:(NSPointerFunctions *)functions capacity:(NSUInteger)initialCapacity
      • + (NSHashTable *)hashTableWithOptions:(NSPointerFunctionsOptions)options;
      • + (id)hashTableWithWeakObjects;
      • + (NSHashTable *)weakObjectsHashTable;

在创建NSHashTable对象时,会传NSPointerFunctionsOptions参数,列举如下:

  • NSHashTableStrongMemory
    • 将HashTable容器内的对象引用计数+1一次
  • NSHashTableZeroingWeakMemory
    • 在OSX 10.8之后已经废弃
  • NSHashTableCopyIn
    • 将添加到容器的对象通过NSCopying中的方法,复制一个新的对象存入HashTable容器
  • NSHashTableObjectPointerPersonality
    • 使用移位指针(shifted pointer)来做hash检测及确定两个对象是否相等;
  • NSHashTableWeakMemory
    • 不会修改HashTable容器内对象元素的引用计数,并且对象释放后,会被自动移除

对于我们来说,NSHashTable吸引力比较大的即NSHashTableWeakMemory特性.
使用一段代码来展示功能:

#import <Foundation/Foundation.h>

@interface HHHuman : NSObject

@property (nonatomic ,strong) NSString      *name;
@property (nonatomic ,strong) NSHashTable   *family;

+ (instancetype) humanWithName:(NSString *)n;

@end

@implementation HHHuman

+ (instancetype) humanWithName:(NSString *)n
{
    HHHuman *human = [[HHHuman alloc] init];
    human.name = n;
    human.family = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];
    [human.family addObject:human];

    return [human autorelease];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s retainCount is %lu",self.name,[self retainCount]];
}
- (void)dealloc
{
    self.name = nil;
    self.family = nil;
    [super dealloc];
}

@end

int main(int argc, const char * argv[])
{
    //创建一个NSHashTableWeakMemory特性的HashTable对象
    NSHashTable *hash_tab = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];

    //创建自动释放池对象
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //通过便利构造器获取一个name属性是lewis的human对象
    HHHuman *human = [HHHuman humanWithName:@"lewis"];

    //将该对象添加到HashTable容器中
    [hash_tab addObject:human];
    
    //释放之前打印human
    NSLog(@"before pool:%@",human);
    
    //将自动释放池释放掉
    [pool drain];
    
    //释放之后打印hash_tab
    NSLog(@"after pool:%@",hash_tab);
    return 0;
}

在控制台输出的结果如下

before pool:lewis's retainCount is 1
after pool:NSHashTable {
}

我们可以看到,当pool对象释放时,human的引用计数会执行一次-1,human对象在内存中就会自动释放,并且相应的hash_tab对象中的对象也会被自动移除.
而我们在创建hash_tab时使用的是NSHashTableStrongMemory特性话,那么控制台输出的结果如下:

before pool:lewis's retainCount is 2
after pool:NSHashTable {
[13] lewis's retainCount is 1
}


有了NSHashTable就可以完成我们文章一开始的需求了.

#import <Foundation/Foundation.h>

@interface HHHuman : NSObject

@property (nonatomic ,strong) NSString      *name;
@property (nonatomic ,strong) NSHashTable   *family;

+ (instancetype) humanWithName:(NSString *)n;

@end

@implementation HHHuman

+ (instancetype) humanWithName:(NSString *)n
{
    HHHuman *human = [[HHHuman alloc] init];
    human.name = n;
    human.family = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];
    [human.family addObject:human];

    return [human autorelease];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@'s retainCount is %lu",self.name,[self retainCount]];
}
- (void)dealloc
{
    self.name = nil;
    self.family = nil;
    [super dealloc];
}

@end

NSHashTable可以使用的函数

typedef struct {NSUInteger _pi; NSUInteger _si; void *_bs;} NSHashEnumerator;

FOUNDATION_EXPORT void NSFreeHashTable(NSHashTable *table);
FOUNDATION_EXPORT void NSResetHashTable(NSHashTable *table);
FOUNDATION_EXPORT BOOL NSCompareHashTables(NSHashTable *table1, NSHashTable *table2);
FOUNDATION_EXPORT NSHashTable *NSCopyHashTableWithZone(NSHashTable *table, NSZone *zone);
FOUNDATION_EXPORT void *NSHashGet(NSHashTable *table, const void *pointer);
FOUNDATION_EXPORT void NSHashInsert(NSHashTable *table, const void *pointer);
FOUNDATION_EXPORT void NSHashInsertKnownAbsent(NSHashTable *table, const void *pointer);
FOUNDATION_EXPORT void *NSHashInsertIfAbsent(NSHashTable *table, const void *pointer);
FOUNDATION_EXPORT void NSHashRemove(NSHashTable *table, const void *pointer);
FOUNDATION_EXPORT NSHashEnumerator NSEnumerateHashTable(NSHashTable *table);
FOUNDATION_EXPORT void *NSNextHashEnumeratorItem(NSHashEnumerator *enumerator);
FOUNDATION_EXPORT void NSEndHashTableEnumeration(NSHashEnumerator *enumerator);
FOUNDATION_EXPORT NSUInteger NSCountHashTable(NSHashTable *table);
FOUNDATION_EXPORT NSString *NSStringFromHashTable(NSHashTable *table);
FOUNDATION_EXPORT NSArray *NSAllHashTableObjects(NSHashTable *table);


NSMapTable


  • NSMapTable
    • 构造函数
      • - (instancetype)initWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions capacity:(NSUInteger)initialCapacity;
      • - (instancetype)initWithKeyPointerFunctions:(NSPointerFunctions *)keyFunctions valuePointerFunctions:(NSPointerFunctions *)valueFunctions capacity:(NSUInteger)initialCapacity;
      • + (NSMapTable *)mapTableWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions;
      • + (NSMapTable *)strongToStrongObjectsMapTable;
      • + (NSMapTable *)weakToStrongObjectsMapTable;
      • + (NSMapTable *)strongToWeakObjectsMapTable;
      • + (NSMapTable *)weakToWeakObjectsMapTable;

NSMapTable对象类似与NSDictionary的数据结构,但是NSMapTable功能比NSDictionary对象要多的功能就是可以设置keyvalue的NSPointerFunctionsOptions特性!其他的用法与NSDictionary相同.

NSMapTable可以使用的函数

FOUNDATION_EXPORT void NSFreeMapTable(NSMapTable *table);
FOUNDATION_EXPORT void NSResetMapTable(NSMapTable *table);
FOUNDATION_EXPORT BOOL NSCompareMapTables(NSMapTable *table1, NSMapTable *table2);
FOUNDATION_EXPORT NSMapTable *NSCopyMapTableWithZone(NSMapTable *table, NSZone *zone);
FOUNDATION_EXPORT BOOL NSMapMember(NSMapTable *table, const void *key, void **originalKey, void **value);
FOUNDATION_EXPORT void *NSMapGet(NSMapTable *table, const void *key);
FOUNDATION_EXPORT void NSMapInsert(NSMapTable *table, const void *key, const void *value);
FOUNDATION_EXPORT void NSMapInsertKnownAbsent(NSMapTable *table, const void *key, const void *value);
FOUNDATION_EXPORT void *NSMapInsertIfAbsent(NSMapTable *table, const void *key, const void *value);
FOUNDATION_EXPORT void NSMapRemove(NSMapTable *table, const void *key);
FOUNDATION_EXPORT NSMapEnumerator NSEnumerateMapTable(NSMapTable *table);
FOUNDATION_EXPORT BOOL NSNextMapEnumeratorPair(NSMapEnumerator *enumerator, void **key, void **value);
FOUNDATION_EXPORT void NSEndMapTableEnumeration(NSMapEnumerator *enumerator);
FOUNDATION_EXPORT NSUInteger NSCountMapTable(NSMapTable *table);
FOUNDATION_EXPORT NSString *NSStringFromMapTable(NSMapTable *table);
FOUNDATION_EXPORT NSArray *NSAllMapTableKeys(NSMapTable *table);
FOUNDATION_EXPORT NSArray *NSAllMapTableValues(NSMapTable *table);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容