iOS基础知识IOS

不常见集合NSHashTable和NSMapTable

2020-11-21  本文已影响0人  lenka01

NSArray,NSSet,NSDictionary是平时常用的数据类型,今天想说的是另外两个比较高阶的集合NSHashTableNSMapTable

NSHashTable

首先我们看下官方的解释:

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).

大概意思就是说NSHashTable是一种类似NSSet一样的集合。但是它具有更广泛的可用内存语义。能够对持有对象以弱引用的方式存储。大家都知道平时用的NSArrayNSSet都是对对应的强持有(强引用),结果就是在某些场合达不到理想效果。

那么NSHashTable有哪些使用场景呢?

不知道同学们有没有遇到过类似场景需求,某工具类需要持有多个代理对象,方便后续逐一回调。比如某个订阅器订阅了某个通知,然后通知到来时需要下发给每一个需要响应的页面,这些页面肯定是要实现订阅器的代理方法的。所以,遇到这种场景时,我们可能要注意了。不能使用常用数据类型来管理多个代理者了(因为代理者不能被强引用,会有循环引用问题),此时我们可以采用NSHashTable的弱引用特性。好了,不多说了,直接上代码解释吧。
有这么个单例类:

// 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文件实现如下:

#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

看到了没,这里我们使用的是weakObjectsHashTable来实现。
然后代理者地方实现:

self.sharedObject = [SharedObject shared];
[self.sharedObject addDelegate:self];

大家可以试试,把weakObjectsHashTable换成NSArray看看什么效果?(结果应该是循环引用,导致代理者无法被释放)

NSHashTable使用介绍

大家可以看到,NSHashTable有如下几个初始化方法:

- (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初始化时我们看到有个NSPointerFunctionsOptions参数,它有如下集中枚举值:

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
};

我们可以发现,默认是NSPointerFunctionsStrongMemory,即内存强引用。效果和NSSet类似,会造成元素强引用,聪明的你当然能发现,刚好有一个NSPointerFunctionsWeakMemory。其他方法和常规NSSet使用类似。

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

大概意思就是:NSMapTableNSDictionary类似,也拥有强大的内存管理能力。分别对keyvalue都可以进行不同内存引用管理。
还是拿上面那个例子说明:新增一个需求,能够添加代理者和回调线程
此时我们不好用NSHashTable来实现了,因为NSHashTable只能够添加一个参数(当然要实现也是可以的,采用中间件思想,用一个新对象来分别持有这两个参数)。 然而也有另外一种思路是采用NSMapTable我们刚好可以把两个参数分别作为key-value存储起来。好了,下面直接上代码吧。

#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

新增一个接口方法支持传两个参数。

#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,因为key需要能够实现NSCoping协议,同NSDictiony类似。
        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

我们在选择时根据需求来选择,这里有个NSPointerFunctionsOptions提供的值类型也是和内存相关。

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
};

可以看到,默认是NSPointerFunctionsStrongMemory强引用值,这里我们推荐使用NSPointerFunctionsWeakMemory来搭配使用。
然后几个类方法也分别对应了四种搭配。如下:
strongToStrongObjectsMapTable相当于

[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions: NSPointerFunctionsStrongMemory];

weakToStrongObjectsMapTable相当于:

[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];

strongToWeakObjectsMapTable相当于:

[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory];

weakToWeakObjectsMapTable相当于:

[NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions: NSPointerFunctionsWeakMemory];

好了,简单的梳理就介绍到这了。后面有更深入的理解时再来完成补充,谢谢。

上一篇下一篇

猜你喜欢

热点阅读