像NSArray,NSSet,NSDictionary是平時(shí)常用的數(shù)據(jù)類(lèi)型,今天想說(shuō)的是另外兩個(gè)比較高階的集合NSHashTable和NSMapTable。
NSHashTable
首先我們看下官方的解釋?zhuān)?/p>
A collection similar to a set, but with broader range of available memory semantics.
The hash table is modeled after NSSet with the following differences:
* It can hold weak references to its members.
* Its members may be copied on input or may use pointer identity for equality and hashing.
* It can contain arbitrary pointers (its members are not constrained to being objects).
大概意思就是說(shuō)NSHashTable是一種類(lèi)似NSSet一樣的集合。但是它具有更廣泛的可用內(nèi)存語(yǔ)義。能夠?qū)Τ钟袑?duì)象以弱引用的方式存儲(chǔ)。大家都知道平時(shí)用的NSArray和NSSet都是對(duì)對(duì)應(yīng)的強(qiáng)持有(強(qiáng)引用),結(jié)果就是在某些場(chǎng)合達(dá)不到理想效果。
那么NSHashTable有哪些使用場(chǎng)景呢?
不知道同學(xué)們有沒(méi)有遇到過(guò)類(lèi)似場(chǎng)景需求,某工具類(lèi)需要持有多個(gè)代理對(duì)象,方便后續(xù)逐一回調(diào)。比如某個(gè)訂閱器訂閱了某個(gè)通知,然后通知到來(lái)時(shí)需要下發(fā)給每一個(gè)需要響應(yīng)的頁(yè)面,這些頁(yè)面肯定是要實(shí)現(xiàn)訂閱器的代理方法的。所以,遇到這種場(chǎng)景時(shí),我們可能要注意了。不能使用常用數(shù)據(jù)類(lèi)型來(lái)管理多個(gè)代理者了(因?yàn)榇碚卟荒鼙粡?qiáng)引用,會(huì)有循環(huán)引用問(wèn)題),此時(shí)我們可以采用NSHashTable的弱引用特性。好了,不多說(shuō)了,直接上代碼解釋吧。
有這么個(gè)單例類(lèi):
// SharedObject.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SharedObject : NSObject
@property (nonatomic,strong,readonly)NSArray *delegates;
+ (instancetype)shared;
- (void)addDelegate:(id)delegate;
@end
NS_ASSUME_NONNULL_END
.m文件實(shí)現(xiàn)如下:
#import "SharedObject.h"
@implementation SharedObject
{
NSHashTable *_hashTable;
}
+ (instancetype)shared {
static SharedObject *object = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object = [[self alloc] init];
});
return object;
};
- (instancetype)init {
if (self=[super init]) {
_hashTable = [NSHashTable weakObjectsHashTable];
}
return self;;
}
- (void)addDelegate:(id)delegate {
if (delegate) {
[_hashTable addObject:delegate];
}
}
- (NSArray *)delegates {
return _hashTable.allObjects;
}
@end
看到了沒(méi),這里我們使用的是weakObjectsHashTable來(lái)實(shí)現(xiàn)。
然后代理者地方實(shí)現(xiàn):
self.sharedObject = [SharedObject shared];
[self.sharedObject addDelegate:self];
大家可以試試,把weakObjectsHashTable換成NSArray看看什么效果?(結(jié)果應(yīng)該是循環(huán)引用,導(dǎo)致代理者無(wú)法被釋放)
NSHashTable使用介紹
大家可以看到,NSHashTable有如下幾個(gè)初始化方法:
- (instancetype)initWithOptions:(NSPointerFunctionsOptions)options capacity:(NSUInteger)initialCapacity NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithPointerFunctions:(NSPointerFunctions *)functions capacity:(NSUInteger)initialCapacity NS_DESIGNATED_INITIALIZER;
+ (NSHashTable<ObjectType> *)hashTableWithOptions:(NSPointerFunctionsOptions)options;
+ (NSHashTable<ObjectType> *)weakObjectsHashTable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
使用init初始化時(shí)我們看到有個(gè)NSPointerFunctionsOptions參數(shù),它有如下集中枚舉值:
typedef NS_OPTIONS(NSUInteger, NSPointerFunctionsOptions) {
// Memory options are mutually exclusive
// default is strong
NSPointerFunctionsStrongMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (0UL << 0), // use strong write-barrier to backing store; use GC memory on copyIn
NSPointerFunctionsZeroingWeakMemory API_DEPRECATED("GC no longer supported", macos(10.5, 10.8)) API_UNAVAILABLE(ios, watchos, tvos) = (1UL << 0), // deprecated; uses GC weak read and write barriers, and dangling pointer behavior otherwise
NSPointerFunctionsOpaqueMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (2UL << 0),
NSPointerFunctionsMallocMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (3UL << 0), // free() will be called on removal, calloc on copyIn
NSPointerFunctionsMachVirtualMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (4UL << 0),
NSPointerFunctionsWeakMemory API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)) = (5UL << 0), // uses weak read and write barriers appropriate for ARC
// Personalities are mutually exclusive
// default is object. As a special case, 'strong' memory used for Objects will do retain/release under non-GC
NSPointerFunctionsObjectPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (0UL << 8), // use -hash and -isEqual, object description
NSPointerFunctionsOpaquePersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (1UL << 8), // use shifted pointer hash and direct equality
NSPointerFunctionsObjectPointerPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (2UL << 8), // use shifted pointer hash and direct equality, object description
NSPointerFunctionsCStringPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (3UL << 8), // use a string hash and strcmp, description assumes UTF-8 contents; recommended for UTF-8 (or ASCII, which is a subset) only cstrings
NSPointerFunctionsStructPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (4UL << 8), // use a memory hash and memcmp (using size function you must set)
NSPointerFunctionsIntegerPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (5UL << 8), // use unshifted value as hash & equality
NSPointerFunctionsCopyIn API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (1UL << 16), // the memory acquire function will be asked to allocate and copy items on input
};
我們可以發(fā)現(xiàn),默認(rèn)是NSPointerFunctionsStrongMemory,即內(nèi)存強(qiáng)引用。效果和NSSet類(lèi)似,會(huì)造成元素強(qiáng)引用,聰明的你當(dāng)然能發(fā)現(xiàn),剛好有一個(gè)NSPointerFunctionsWeakMemory。其他方法和常規(guī)NSSet使用類(lèi)似。
- (void)addObject:(nullable ObjectType)object;
- (void)removeObject:(nullable ObjectType)object;
- (void)removeAllObjects;
NSMapTable介紹
官方介紹是:
A collection similar to a dictionary, but with a broader range of available memory semantics.
The map table is modeled after [NSDictionary] with the following differences:
* Keys and/or values are optionally held “weakly” such that entries are removed when one of the objects is reclaimed.
* Its keys or values may be copied on input or may use pointer identity for equality and hashing.
* It can contain arbitrary pointers (its contents are not constrained to being objects).
大概意思就是:NSMapTable和NSDictionary類(lèi)似,也擁有強(qiáng)大的內(nèi)存管理能力。分別對(duì)key和value都可以進(jìn)行不同內(nèi)存引用管理。
還是拿上面那個(gè)例子說(shuō)明:新增一個(gè)需求,能夠添加代理者和回調(diào)線程。
此時(shí)我們不好用NSHashTable來(lái)實(shí)現(xiàn)了,因?yàn)?code>NSHashTable只能夠添加一個(gè)參數(shù)(當(dāng)然要實(shí)現(xiàn)也是可以的,采用中間件思想,用一個(gè)新對(duì)象來(lái)分別持有這兩個(gè)參數(shù))。 然而也有另外一種思路是采用NSMapTable我們剛好可以把兩個(gè)參數(shù)分別作為key-value存儲(chǔ)起來(lái)。好了,下面直接上代碼吧。
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SharedObject : NSObject
@property (nonatomic,strong,readonly)NSArray *delegates;
+ (instancetype)shared;
- (void)addDelegate:(id)delegate dispathQueue:(dispatch_queue_t)queue_t;
@end
NS_ASSUME_NONNULL_END
新增一個(gè)接口方法支持傳兩個(gè)參數(shù)。
#import "SharedObject.h"
@implementation SharedObject
{
NSMapTable *_mapTable;
}
+ (instancetype)shared {
static SharedObject *object = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object = [[self alloc] init];
});
return object;
};
- (instancetype)init {
if (self=[super init]) {
_mapTable = [NSMapTable weakToStrongObjectsMapTable];
}
return self;;
}
- (void)addDelegate:(id)delegate dispathQueue:(dispatch_queue_t)queue_t {
if (delegate) {
//這里需要在delegate上包一層作為key,因?yàn)閗ey需要能夠?qū)崿F(xiàn)NSCoping協(xié)議,同NSDictiony類(lèi)似。
NSMutableOrderedSet *orderSet = [NSMutableOrderedSet orderedSet];
[orderSet addObject:delegate];
[_mapTable setObject:queue_t?queue_t:dispatch_get_main_queue() forKey:orderSet.copy];
}
}
- (NSArray *)delegates {
return _mapTable.dictionaryRepresentation.allKeys;
}
@end
代理者使用地方
self.sharedObject = [SharedObject shared];
[self.sharedObject addDelegate:self dispathQueue:dispatch_get_main_queue()];
NSMapTable使用介紹
我們可以看到NSMapTable有下面幾種初始化方法:
- (instancetype)initWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions capacity:(NSUInteger)initialCapacity NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithKeyPointerFunctions:(NSPointerFunctions *)keyFunctions valuePointerFunctions:(NSPointerFunctions *)valueFunctions capacity:(NSUInteger)initialCapacity NS_DESIGNATED_INITIALIZER;
+ (NSMapTable<KeyType, ObjectType> *)mapTableWithKeyOptions:(NSPointerFunctionsOptions)keyOptions valueOptions:(NSPointerFunctionsOptions)valueOptions;
+ (NSMapTable<KeyType, ObjectType> *)strongToStrongObjectsMapTable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
+ (NSMapTable<KeyType, ObjectType> *)weakToStrongObjectsMapTable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); // entries are not necessarily purged right away when the weak key is reclaimed
+ (NSMapTable<KeyType, ObjectType> *)strongToWeakObjectsMapTable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
+ (NSMapTable<KeyType, ObjectType> *)weakToWeakObjectsMapTable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); // entries are not necessarily purged right away when the weak key or object is reclaimed
我們?cè)谶x擇時(shí)根據(jù)需求來(lái)選擇,這里有個(gè)NSPointerFunctionsOptions提供的值類(lèi)型也是和內(nèi)存相關(guān)。
typedef NS_OPTIONS(NSUInteger, NSPointerFunctionsOptions) {
// Memory options are mutually exclusive
// default is strong
NSPointerFunctionsStrongMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (0UL << 0), // use strong write-barrier to backing store; use GC memory on copyIn
NSPointerFunctionsZeroingWeakMemory API_DEPRECATED("GC no longer supported", macos(10.5, 10.8)) API_UNAVAILABLE(ios, watchos, tvos) = (1UL << 0), // deprecated; uses GC weak read and write barriers, and dangling pointer behavior otherwise
NSPointerFunctionsOpaqueMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (2UL << 0),
NSPointerFunctionsMallocMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (3UL << 0), // free() will be called on removal, calloc on copyIn
NSPointerFunctionsMachVirtualMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (4UL << 0),
NSPointerFunctionsWeakMemory API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)) = (5UL << 0), // uses weak read and write barriers appropriate for ARC
// Personalities are mutually exclusive
// default is object. As a special case, 'strong' memory used for Objects will do retain/release under non-GC
NSPointerFunctionsObjectPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (0UL << 8), // use -hash and -isEqual, object description
NSPointerFunctionsOpaquePersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (1UL << 8), // use shifted pointer hash and direct equality
NSPointerFunctionsObjectPointerPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (2UL << 8), // use shifted pointer hash and direct equality, object description
NSPointerFunctionsCStringPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (3UL << 8), // use a string hash and strcmp, description assumes UTF-8 contents; recommended for UTF-8 (or ASCII, which is a subset) only cstrings
NSPointerFunctionsStructPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (4UL << 8), // use a memory hash and memcmp (using size function you must set)
NSPointerFunctionsIntegerPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (5UL << 8), // use unshifted value as hash & equality
NSPointerFunctionsCopyIn API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = (1UL << 16), // the memory acquire function will be asked to allocate and copy items on input
};
可以看到,默認(rèn)是NSPointerFunctionsStrongMemory強(qiáng)引用值,這里我們推薦使用NSPointerFunctionsWeakMemory來(lái)搭配使用。
然后幾個(gè)類(lèi)方法也分別對(duì)應(yīng)了四種搭配。如下:
strongToStrongObjectsMapTable相當(dāng)于
[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions: NSPointerFunctionsStrongMemory];
weakToStrongObjectsMapTable相當(dāng)于:
[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];
strongToWeakObjectsMapTable相當(dāng)于:
[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory];
weakToWeakObjectsMapTable相當(dāng)于:
[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions: NSPointerFunctionsWeakMemory];
好了,簡(jiǎn)單的梳理就介紹到這了。后面有更深入的理解時(shí)再來(lái)完成補(bǔ)充,謝謝。