[转][iOS]NSHashTable & NSMapTable
NSSet and NSDictionary, along with NSArray are the workhorse collection classes of Foundation. Unlike other standard libraries, implementation details are hidden from developers, allowing them to write simple code and trust that it will be (reasonably) performant.
However, even the best abstractions break down; their underlying assumptions overturned. In these cases, developers either venture further down the abstraction, or, if available use a more general-purpose solution.
For NSSet and NSDictionary, the breaking assumption was in the memory behavior when storing objects in the collection. For NSSet, objects are a strongly referenced, as are NSDictionary values. Keys, on the other hand, are copied by NSDictionary. If a developer wanted to store a weak value, or use a non-<NSCopying>-conforming object as a key, they could be clever and use NSValue +valueWithNonretainedObject. Or, as of iOS 6 (and as far back as OS X Leopard), they could use NSHashTable or NSMapTable, the more general-case counterparts to NSSet or NSDictionary, respectively.
So without further ado, here's everything you need to know about two of the more obscure members of Foundation's collection classes:
NSHashTable
NSHashTable is a general-purpose analogue of NSSet. Contrasted with the behavior of NSSet / NSMutableSet, NSHashTable has the following characteristics:
NSSet/NSMutableSetholdsstrongreferences to members, which are tested for hashing and equality using the methodshashandisEqual:.NSHashTableis mutable, without an immutable counterpart.NSHashTablecan holdweakreferences to its members.NSHashTablecancopymembers on input.NSHashTablecan contain arbitrary pointers, and use pointer identity for equality and hashing checks.
Usage
NSHashTable *hashTable = [NSHashTable hashTableWithOptions:NSPointerFunctionsCopyIn];
[hashTable addObject:@"foo"];
[hashTable addObject:@"bar"];
[hashTable addObject:@42];
[hashTable removeObject:@"bar"];
NSLog(@"Members: %@", [hashTable allObjects]);
NSHashTable objects are initialized with an option for any of the following behaviors. Deprecated enum values are due to NSHashTable being ported from Garbage-Collected OS X to ARC-ified iOS. Other values are aliased to options defined by NSPointerFunctions, which will be covered next week on NSHipster.
NSHashTableStrongMemory: Equal toNSPointerFunctionsStrongMemory. This is the default behavior, equivalent toNSSetmember storage.NSHashTableWeakMemory: Equal toNSPointerFunctionsWeakMemory. Uses weak read and write barriers. UsingNSPointerFunctionsWeakMemory, object references will turn toNULLon last release.NSHashTableZeroingWeakMemory: This option has been deprecated. Instead use theNSHashTableWeakMemoryoption.NSHashTableCopyIn: Use the memory acquire function to allocate and copy items on input (seeNSPointerFunction -acquireFunction). Equal toNSPointerFunctionsCopyIn.NSHashTableObjectPointerPersonality: Use shifted pointer for the hash value and direct comparison to determine equality; use the description method for a description. Equal toNSPointerFunctionsObjectPointerPersonality.
NSMapTable
NSMapTable is a general-purpose analogue of NSDictionary. Contrasted with the behavior of NSDictionary / NSMutableDictionary, NSMapTable has the following characteristics:
NSDictionary/NSMutableDictionarycopies keys, and holds strong references to values.NSMapTableis mutable, without an immutable counterpart.NSMapTablecan hold keys and values withweakreferences, in such a way that entries are removed when either the key or value is deallocated.NSMapTablecancopyits values on input.NSMapTablecan contain arbitrary pointers, and use pointer identity for equality and hashing checks.
Usage
Instances where one might use NSMapTable include non-copyable keys and storing weak references to keyed delegates or another kind of weak object.
id delegate = ...;
NSMapTable *mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
valueOptions:NSMapTableWeakMemory];
[mapTable setObject:delegate forKey:@"foo"];
NSLog(@"Keys: %@", [[mapTable keyEnumerator] allObjects]);
NSMapTable objects are initialized with options specifying behavior for both keys and values, using the following enum values:
NSMapTableStrongMemory: Specifies a strong reference from the map table to its contents.NSMapTableWeakMemory: Uses weak read and write barriers appropriate for ARC or GC. UsingNSPointerFunctionsWeakMemory, object references will turn toNULLon last release. Equal toNSMapTableZeroingWeakMemory.NSHashTableZeroingWeakMemory: This option has been superseded by theNSMapTableWeakMemoryoption.NSMapTableCopyIn: Use the memory acquire function to allocate and copy items on input (see acquireFunction (seeNSPointerFunction -acquireFunction). Equal to NSPointerFunctionsCopyIn.NSMapTableObjectPointerPersonality: Use shifted pointer hash and direct equality, object description. Equal toNSPointerFunctionsObjectPointerPersonality.
Subscripting
NSMapTable doesn't implement object subscripting, but it can be trivially added in a category. NSDictionary's NSCopying requirement for keys belongs to NSDictionary alone:
@implementation NSMapTable (NSHipsterSubscripting)
- (id)objectForKeyedSubscript:(id)key
{
return [self objectForKey:key];
}
- (void)setObject:(id)obj forKeyedSubscript:(id)key
{
[self setObject:obj forKey:key];
}
@end
As always, it's important to remember that programming is not about being clever: always approach a problem from the highest viable level of abstraction. NSSet and NSDictionary are great classes. For 99% of problems, they are undoubtedly the correct tool for the job. If, however, your problem has any of the particular memory management constraints described above, then NSHashTable & NSMapTablemay be worth a look.
---------
作为delegate弱引用的集合再合适不过了。
[转][iOS]NSHashTable & NSMapTable的更多相关文章
- mysqldump:Couldn't execute 'show create table `tablename`': Table tablename' doesn't exist (1146)
遇到了一个错误mysqldump: Couldn't execute 'show create table `CONCURRENCY_ERRORS`': Table INVOICE_OLD.CONCU ...
- ORA-01747: user.table.column, table.column 或列说明无效
Oracle.DataAccess.Client.OracleException ORA-01747: user.table.column, table.column 或列说明无效 原因1: 查了一下 ...
- SQLServer temporary table and table variable
Temporary tables are created in tempdb. The name "temporary" is slightly misleading, for ...
- Oracle10g 回收站及彻底删除table : drop table xx purge
drop后的表被放在回收站(user_recyclebin)里,而不是直接删除掉.这样,回收站里的表信息就可以被恢复,或彻底清除. 1.通过查询回收站user_recyclebin获取被删除的表信息, ...
- user.table.column, table.column 或列说明无效
Oracle统计采用别名出错(user.table.column, table.column 或列说明无效) >>>>>>>>>>>& ...
- lua中打印所以类型功能实现table嵌套table
lua中打印所以类型功能实现 本人測试 number.string.bool.nil.table嵌套table.userdata没问题 共享一下有什么问题请拍砖 代码例如以下 cclog = func ...
- 使用vue的v-for生成table , 给table加上序号
现在有一个使用mybatis的分页插件生成的table,table中数据是通过vue获得的 , 前台显示使用<tr v-for="item in items"> 后台v ...
- 表优化 altering table OPTIMIZE TABLE `sta_addr_copy`
表优化 altering table OPTIMIZE TABLE `sta_addr_copy` [总结] 1.实际测试的结果是,在state sqlaltering table OPTIMIZE ...
- MySQL check table/optimize table/analyze table/REPAIR TABLE
MySQL check table/optimize table/analyze table/REPAIR TABLE 转自:https://www.cnblogs.com/datastack/p/3 ...
随机推荐
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...
- python支持mysql
MySQLdb只支持Python2.,还不支持3. 可以用PyMySQL代替.安装方法:pip install PyMySQL 然后在需要的项目中,把 init.py中添加两行: import pym ...
- HTML5 之拖放(drag与drop)
拖放(Drag 和 drop)是 HTML5 标准的组成部分. 拖放是一种常见的特性,即抓取对象以后拖到另一个位置. 在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放. HTML5 拖放实例 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统-分配角色给用户
系列目录 由于之前做了将权限赋给角色,还需要做将角色组赋给用户,和将用户赋给角色组,一个用户可以拥有多个角色组,一个角色组包含多个用户,打开模块管理,添加一个分配的操作码 并在 角色权限设置授权给他 ...
- 读书笔记--SQL必知必会12--联结表
12.1 联结 联结(join),利用SQL的SELECT在数据查询的执行中联结表. 12.1.1 关系表 关系数据库中,关系表的设计是把信息分解成多个表,一类数据一个表,各表通过某些共同的值互相关联 ...
- 你真的会玩SQL吗?透视转换的艺术
你真的会玩SQL吗?系列目录 你真的会玩SQL吗?之逻辑查询处理阶段 你真的会玩SQL吗?和平大使 内连接.外连接 你真的会玩SQL吗?三范式.数据完整性 你真的会玩SQL吗?查询指定节点及其所有父节 ...
- 剖析并利用Visual Studio Code在Mac上编译、调试c#程序
0x00 前言 一周多以前的微软的Build大会上,微软发布了一个让很多人眼前一亮的工具,也是本文的主角——Visual Studio Code.很多使用Windows的朋友都很高兴,认为又多了一个很 ...
- [Ant]Ant简易教程
前言 Apache Ant,是一个将软件编译.测试.部署等步骤联系在一起加以自动化的一个工具,大多用于Java环境中的软件开发.由Apache软件基金会所提供. Ant是纯Java语言编写的,所以具有 ...
- User Growth Using Deeplink. (part1)
转载请注明来源 http://www.cnblogs.com/hucn/p/5917924.html 活跃人数是衡量app一项关键指标, dau, mau, 有了流量才能给业务发展提供养分和空间. a ...
- VS2015 Update2中有关cordova和xamarin安装的问题
最近VS2015出了Update2,当然是第一时间进行了安装,中间过程曲折,反复安装卸载n次,也算是获得了一定的安装经验值.现在说一下经常出的问题. Update2里最吸引人的当然是跨平台开发的部分, ...