iCoder

iOS数据结构NSMapTable,NSHashTable和NS

2020-09-10  本文已影响0人  Trigger_o

map就是键值对集合

hashMap是数组和链表的组合,数组是主体,链表用来处理其他问题如hash值冲突
hashMap是如何工作的

在iOS中的应用:

//创建一个NSMapTable对象
NSMapTable *mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableCopyIn valueOptions:NSMapTableWeakMemory];
[mapTable setObject:self forKey:@"delegate"];

key和value的内存策略

static const NSPointerFunctionsOptions NSMapTableStrongMemory API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = NSPointerFunctionsStrongMemory;
static const NSPointerFunctionsOptions NSMapTableZeroingWeakMemory API_DEPRECATED("GC no longer supported", macos(10.5,10.8)) API_UNAVAILABLE(ios, watchos, tvos) = NSPointerFunctionsZeroingWeakMemory;
static const NSPointerFunctionsOptions NSMapTableCopyIn API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = NSPointerFunctionsCopyIn;
static const NSPointerFunctionsOptions NSMapTableObjectPointerPersonality API_AVAILABLE(macos(10.5), ios(6.0), watchos(2.0), tvos(9.0)) = NSPointerFunctionsObjectPointerPersonality;
static const NSPointerFunctionsOptions NSMapTableWeakMemory API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)) = NSPointerFunctionsWeakMemory;

NSPointerFunctionsStrongMemory : 引用计数+1
NSMapTableZeroingWeakMemory :已废弃
NSPointerFunctionsCopyIn : 遵循NSCopying协议 copy一份
NSPointerFunctionsObjectPointerPersonality : 使用偏移后指针,进行hash和直接比较等同性
NSPointerFunctionsWeakMemory : 保存一个week指针,不会增加引用计数

当key或value使用NSPointerFunctionsWeakMemory时,只要有一个被释放,整项键值对都会被移除.

NSHashTable *hashTable = [NSHashTable hashTableWithOptions:NSPointerFunctionsCopyIn];
    [hashTable addObject:@"hello"];
    [hashTable addObject:@10];
    [hashTable addObject:@"world"];
    [hashTable removeObject:@"world"];
    NSLog(@"Members: %@", [hashTable allObjects]);

-NSPointerArray
NSPointerArray是NSArray的通用版,可变,可以存储NULL,并且算作一个元素,可以直接set count,可以存放所有指针类型(void *),并且遵循NSFastEnumeration可以快速遍历.

NSPointerArray *pointerArray = [[NSPointerArray alloc]initWithOptions:NSPointerFunctionsStrongMemory];
    pointerArray.count = 5;
    [pointerArray allObjects];
    // 指定索引处的指针
    void *point = [pointerArray pointerAtIndex:0];//nil
    // 数组中添加指针对象
    [pointerArray addPointer:@"2"];//(2)
    // 移除指定索引处的元素
    [pointerArray removePointerAtIndex:0];//(2)
    // 指定索引出插入元素
    [pointerArray insertPointer:@"1" atIndex:0];//(1,2)
    // 替换指定索引处的对象
    [pointerArray replacePointerAtIndex:0 withPointer:@"2"];//(2,2)
    // 删除数组中的nil值
    [pointerArray compact];
    // 获取数组的功能项
    NSPointerFunctions *Functions = [pointerArray pointerFunctions];
上一篇 下一篇

猜你喜欢

热点阅读