[iOS]NSHashTable和NSMapTable用法


一個項(xiàng)目中的需求


在iOS項(xiàng)目開發(fā)過程中,我們經(jīng)常會使用到NSSet凄贩、NSArrayNSDictionary三個類袱讹,它們?yōu)槲覀冊O(shè)計(jì)較友好的數(shù)據(jù)結(jié)構(gòu)時提供了很方便的方法

先準(zhǔn)備本文中將要使用的對象:

#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

在程序開發(fā)過程中,經(jīng)常會用到諸如此類的Model對象.
用法呢也大致會有如下幾種方式:
1.通過有序的數(shù)列進(jìn)行存儲,數(shù)組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);

輸出的結(jié)果如下:

(
    "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.通過統(tǒng)一的關(guān)鍵字進(jìn)行存儲,字典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);

輸出的結(jié)果如下:

(
    "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"
)

通過上述兩個例子我們能夠發(fā)現(xiàn)一個問題,即將對象添加到容器時捷雕,會對該對象的引用技術(shù)+1
這樣就會有可能發(fā)生循環(huán)持有的問題椒丧,例如如下代碼:

@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的實(shí)例對象中包含一個strong修飾的family屬性,但是在family屬性中救巷,又添加了human自身對象壶熏,這樣會造成循環(huán)持有的問題,而導(dǎo)致內(nèi)存泄漏浦译。
但是項(xiàng)目需求又要求我們在該Model對象中完成如此代碼棒假,我們不得已會多創(chuàng)建一個類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


很明顯,大家能夠看到這樣造成了程序代碼的臃腫
根據(jù)上述需求和功能精盅,在iOS6之后帽哑,Objective-C Foundation框架中添加了兩個類分別是NSHashTableNSMapTable

  • NSHashTable
    • 構(gòu)造函數(shù)
      • - (instancetype)initWithOptions:(NSPointerFunctionsOptions)options capacity:(NSUInteger)initialCapacity
      • - (instancetype)initWithPointerFunctions:(NSPointerFunctions *)functions capacity:(NSUInteger)initialCapacity
      • + (NSHashTable *)hashTableWithOptions:(NSPointerFunctionsOptions)options;
      • + (id)hashTableWithWeakObjects;
      • + (NSHashTable *)weakObjectsHashTable;

在創(chuàng)建NSHashTable對象時,會傳NSPointerFunctionsOptions參數(shù)叹俏,列舉如下:

  • NSHashTableStrongMemory
    • 將HashTable容器內(nèi)的對象引用計(jì)數(shù)+1一次
  • NSHashTableZeroingWeakMemory
    • 在OSX 10.8之后已經(jīng)廢棄
  • NSHashTableCopyIn
    • 將添加到容器的對象通過NSCopying中的方法妻枕,復(fù)制一個新的對象存入HashTable容器
  • NSHashTableObjectPointerPersonality
    • 使用移位指針(shifted pointer)來做hash檢測及確定兩個對象是否相等;
  • NSHashTableWeakMemory
    • 不會修改HashTable容器內(nèi)對象元素的引用計(jì)數(shù),并且對象釋放后屡谐,會被自動移除

對于我們來說述么,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[])
{
    //創(chuàng)建一個NSHashTableWeakMemory特性的HashTable對象
    NSHashTable *hash_tab = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];

    //創(chuàng)建自動釋放池對象
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //通過便利構(gòu)造器獲取一個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;
}

在控制臺輸出的結(jié)果如下

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

我們可以看到,當(dāng)pool對象釋放時愕掏,human的引用計(jì)數(shù)會執(zhí)行一次-1度秘,human對象在內(nèi)存中就會自動釋放,并且相應(yīng)的hash_tab對象中的對象也會被自動移除.
而我們在創(chuàng)建hash_tab時使用的是NSHashTableStrongMemory特性話,那么控制臺輸出的結(jié)果如下:

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可以使用的函數(shù)

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
    • 構(gòu)造函數(shù)
      • - (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的數(shù)據(jù)結(jié)構(gòu)亭珍,但是NSMapTable功能比NSDictionary對象要多的功能就是可以設(shè)置keyvalue的NSPointerFunctionsOptions特性!其他的用法與NSDictionary相同.

NSMapTable可以使用的函數(shù)

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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末敷钾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子肄梨,更是在濱河造成了極大的恐慌阻荒,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件众羡,死亡現(xiàn)場離奇詭異侨赡,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)粱侣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進(jìn)店門羊壹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人齐婴,你說我怎么就攤上這事油猫。” “怎么了柠偶?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵情妖,是天一觀的道長。 經(jīng)常有香客問我诱担,道長毡证,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任蔫仙,我火速辦了婚禮料睛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘摇邦。我一直安慰自己恤煞,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布施籍。 她就那樣靜靜地躺著阱州,像睡著了一般。 火紅的嫁衣襯著肌膚如雪法梯。 梳的紋絲不亂的頭發(fā)上苔货,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天犀概,我揣著相機(jī)與錄音,去河邊找鬼夜惭。 笑死姻灶,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的诈茧。 我是一名探鬼主播产喉,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼敢会!你這毒婦竟也來了曾沈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鸥昏,失蹤者是張志新(化名)和其女友劉穎塞俱,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體吏垮,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡障涯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了膳汪。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唯蝶。...
    茶點(diǎn)故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖遗嗽,靈堂內(nèi)的尸體忽然破棺而出粘我,到底是詐尸還是另有隱情,我是刑警寧澤痹换,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布征字,位于F島的核電站,受9級特大地震影響晴音,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缔杉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一锤躁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧或详,春花似錦系羞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至梧乘,卻和暖如春澎迎,著一層夾襖步出監(jiān)牢的瞬間庐杨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工夹供, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留灵份,地道東北人。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓哮洽,卻偏偏與公主長得像填渠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鸟辅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,442評論 2 359

推薦閱讀更多精彩內(nèi)容

  • [iOS]NSHashTable和NSMapTable用法 - 簡書 一個項(xiàng)目中的需求 在iOS項(xiàng)目開發(fā)過程中氛什,我...
    橙娃閱讀 1,008評論 0 0
  • NSSet和NSDictionary 兩個常用的類,它們默認(rèn)假定了其中對象的內(nèi)存行為匪凉。對于NSSet來說枪眉,obje...
    taosiyu閱讀 5,144評論 0 2
  • 在薩德事件這么關(guān)鍵的節(jié)骨眼树绩,國足1:0戰(zhàn)勝韓國可謂幫助所有國人出了口惡氣萨脑,畢竟從體育的角度看我們比韓國強(qiáng)。 然而一...
    好奇動物閱讀 443評論 1 1
  • 似情非晴饺饭, 迷霧重重渤早。 雨打我窗, 清冷隨形瘫俊。
    蠶豆?jié)裨?/span>閱讀 234評論 0 1