美文网首页
[iOS]NSHashTable和NSMapTable用法

[iOS]NSHashTable和NSMapTable用法

作者: 橙娃 | 来源:发表于2016-07-25 21:04 被阅读289次

    [iOS]NSHashTable和NSMapTable用法 - 简书

    一个项目中的需求

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

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

    #import@interfaceHHHuman:NSObject@property(nonatomic,strong)NSString*name;+ (instancetype) humanWithName:(NSString*)n;@end@implementationHHHuman+ (instancetype) humanWithName:(NSString*)n{    HHHuman *human = [[HHHuman alloc] init];    human.name= n;return[human autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s retainCount is %lu",self.name,[selfretainCount]];}- (void)dealloc{self.name=nil;    [superdealloc];}@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"];idlist = @[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"];iddic = @{@"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

    这样就会有可能发生循环持有的问题,例如如下代码:

    @interfaceHHHuman:NSObject@property(nonatomic,strong)NSString*name;@property(nonatomic,strong)NSMutableArray*family;+ (instancetype) humanWithName:(NSString*)n;@end@implementationHHHuman+ (instancetype) humanWithName:(NSString*)n{    HHHuman *human = [[HHHuman alloc] init];    human.name= n;    human.family= [[NSMutableArrayalloc] init];    [human.familyaddObject:human];return[human autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s retainCount is %lu",self.name,[selfretainCount]];}- (void)dealloc{self.name=nil;self.family=nil;    [superdealloc];}@end

    在以上代码中,一个human的实例对象中包含一个strong修饰的family属性,但是在family属性中,又添加了human自身对象,这样会造成循环持有的问题,而导致内存泄漏。

    但是项目需求又要求我们在该Model对象中完成如此代码,我们不得已会多创建一个类HHHumanRelationShip,如下所示:

    #import@interfaceHHHuman:NSObject@property(nonatomic,strong)NSString*name;+ (instancetype) humanWithName:(NSString*)n;@end@implementationHHHuman+ (instancetype) humanWithName:(NSString*)n{    HHHuman *human = [[HHHuman alloc] init];    human.name= n;return[human autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s retainCount is %lu",self.name,[selfretainCount]];}- (void)dealloc{self.name=nil;    [superdealloc];}@end@interfaceHHHumanRelationShip:NSObject@property(nonatomic,strong) HHHuman *human;@property(nonatomic,strong)NSArray*family;+ (instancetype)relationShipWithHuman:(HHHuman *)human family:(NSArray*)members;@end@implementationHHHumanRelationShip+ (instancetype)relationShipWithHuman:(HHHuman *)human family:(NSArray*)members{    HHHumanRelationShip *rs = [[HHHumanRelationShip alloc] init];    rs.human= human;    rs.family= members;return[rs autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s family's member is %@",self.human,self.family];}- (void)dealloc{self.human=nil;self.family=nil;    [superdealloc];}@endintmain(intargc,constchar* 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"];idlist = @[human_1,human_2,human_3,human_4,human_5];    HHHumanRelationShip *relationShip = [HHHumanRelationShip relationShipWithHuman:human_0 family:list];NSLog(@"%@",relationShip);return0;}

    NSHashTable

    很明显,大家能够看到这样造成了程序代码的臃肿

    根据上述需求和功能,在iOS6之后,Objective-C Foundation框架中添加了两个类分别是NSHashTable和NSMapTable

    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@interfaceHHHuman:NSObject@property(nonatomic,strong)NSString*name;@property(nonatomic,strong)NSHashTable*family;+ (instancetype) humanWithName:(NSString*)n;@end@implementationHHHuman+ (instancetype) humanWithName:(NSString*)n{    HHHuman *human = [[HHHuman alloc] init];    human.name= n;    human.family= [NSHashTablehashTableWithOptions:NSHashTableWeakMemory];    [human.familyaddObject:human];return[human autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s retainCount is %lu",self.name,[selfretainCount]];}- (void)dealloc{self.name=nil;self.family=nil;    [superdealloc];}@endintmain(intargc,constchar* argv[]){//创建一个NSHashTableWeakMemory特性的HashTable对象NSHashTable*hash_tab = [NSHashTablehashTableWithOptions:NSHashTableWeakMemory];//创建自动释放池对象NSAutoreleasePool*pool = [[NSAutoreleasePoolalloc] init];//通过便利构造器获取一个name属性是lewis的human对象HHHuman *human = [HHHuman humanWithName:@"lewis"];//将该对象添加到HashTable容器中[hash_tab addObject:human];//释放之前打印humanNSLog(@"before pool:%@",human);//将自动释放池释放掉[pool drain];//释放之后打印hash_tabNSLog(@"after pool:%@",hash_tab);return0;}

    在控制台输出的结果如下

    before pool:lewis'sretainCount is1after pool:NSHashTable{}

    我们可以看到,当pool对象释放时,human的引用计数会执行一次-1,human对象在内存中就会自动释放,并且相应的hash_tab对象中的对象也会被自动移除.

    而我们在创建hash_tab时使用的是NSHashTableStrongMemory特性话,那么控制台输出的结果如下:

    before pool:lewis'sretainCount is2after pool:NSHashTable{[13] lewis'sretainCount is1}

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

    #import@interfaceHHHuman:NSObject@property(nonatomic,strong)NSString*name;@property(nonatomic,strong)NSHashTable*family;+ (instancetype) humanWithName:(NSString*)n;@end@implementationHHHuman+ (instancetype) humanWithName:(NSString*)n{    HHHuman *human = [[HHHuman alloc] init];    human.name= n;    human.family= [NSHashTablehashTableWithOptions:NSHashTableWeakMemory];    [human.familyaddObject:human];return[human autorelease];}- (NSString*)description{return[NSStringstringWithFormat:@"%@'s retainCount is %lu",self.name,[selfretainCount]];}- (void)dealloc{self.name=nil;self.family=nil;    [superdealloc];}@end

    NSHashTable可以使用的函数

    typedefstruct{NSUInteger_pi;NSUInteger_si;void*_bs;}NSHashEnumerator;FOUNDATION_EXPORTvoidNSFreeHashTable(NSHashTable*table);FOUNDATION_EXPORTvoidNSResetHashTable(NSHashTable*table);FOUNDATION_EXPORTBOOLNSCompareHashTables(NSHashTable*table1,NSHashTable*table2);FOUNDATION_EXPORTNSHashTable*NSCopyHashTableWithZone(NSHashTable*table,NSZone*zone);FOUNDATION_EXPORTvoid*NSHashGet(NSHashTable*table,constvoid*pointer);FOUNDATION_EXPORTvoidNSHashInsert(NSHashTable*table,constvoid*pointer);FOUNDATION_EXPORTvoidNSHashInsertKnownAbsent(NSHashTable*table,constvoid*pointer);FOUNDATION_EXPORTvoid*NSHashInsertIfAbsent(NSHashTable*table,constvoid*pointer);FOUNDATION_EXPORTvoidNSHashRemove(NSHashTable*table,constvoid*pointer);FOUNDATION_EXPORTNSHashEnumeratorNSEnumerateHashTable(NSHashTable*table);FOUNDATION_EXPORTvoid*NSNextHashEnumeratorItem(NSHashEnumerator*enumerator);FOUNDATION_EXPORTvoidNSEndHashTableEnumeration(NSHashEnumerator*enumerator);FOUNDATION_EXPORTNSUIntegerNSCountHashTable(NSHashTable*table);FOUNDATION_EXPORTNSString*NSStringFromHashTable(NSHashTable*table);FOUNDATION_EXPORTNSArray*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对象要多的功能就是可以设置key和value的NSPointerFunctionsOptions特性!其他的用法与NSDictionary相同.

    NSMapTable可以使用的函数

    FOUNDATION_EXPORTvoidNSFreeMapTable(NSMapTable*table);FOUNDATION_EXPORTvoidNSResetMapTable(NSMapTable*table);FOUNDATION_EXPORTBOOLNSCompareMapTables(NSMapTable*table1,NSMapTable*table2);FOUNDATION_EXPORTNSMapTable*NSCopyMapTableWithZone(NSMapTable*table,NSZone*zone);FOUNDATION_EXPORTBOOLNSMapMember(NSMapTable*table,constvoid*key,void**originalKey,void**value);FOUNDATION_EXPORTvoid*NSMapGet(NSMapTable*table,constvoid*key);FOUNDATION_EXPORTvoidNSMapInsert(NSMapTable*table,constvoid*key,constvoid*value);FOUNDATION_EXPORTvoidNSMapInsertKnownAbsent(NSMapTable*table,constvoid*key,constvoid*value);FOUNDATION_EXPORTvoid*NSMapInsertIfAbsent(NSMapTable*table,constvoid*key,constvoid*value);FOUNDATION_EXPORTvoidNSMapRemove(NSMapTable*table,constvoid*key);FOUNDATION_EXPORTNSMapEnumeratorNSEnumerateMapTable(NSMapTable*table);FOUNDATION_EXPORTBOOLNSNextMapEnumeratorPair(NSMapEnumerator*enumerator,void**key,void**value);FOUNDATION_EXPORTvoidNSEndMapTableEnumeration(NSMapEnumerator*enumerator);FOUNDATION_EXPORTNSUIntegerNSCountMapTable(NSMapTable*table);FOUNDATION_EXPORTNSString*NSStringFromMapTable(NSMapTable*table);FOUNDATION_EXPORTNSArray*NSAllMapTableKeys(NSMapTable*table);FOUNDATION_EXPORTNSArray*NSAllMapTableValues(NSMapTable*table);

    文/肖浩呗(简书作者)

    原文链接:http://www.jianshu.com/p/de71385930ba

    著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

    相关文章

      网友评论

          本文标题:[iOS]NSHashTable和NSMapTable用法

          本文链接:https://www.haomeiwen.com/subject/pqqnjttx.html