NSDictionary/NSMutableDictionary浅析
我们在使用NSDictionary/NSMutableDictionary时,通常会使用NSString对象作为key,因为key必须遵循NSCopying协议,见NSMutableDictionary中的方法:
- (void)setObject:(ObjectType)anObject forKey:(KeyType <NSCopying>)aKey;
NSDictionary/NSMutableDictionary 提供了 key->object 的映射,从本质上讲,NSDictionary/NSMutableDictionary 中存储的object位置由key来索引的,key对象被copy一份后存入到这个字典私有的空间里,anObject对象则被强引用(下面会举例说明)。
由于对象存储在特定位置,NSDictionary中要求key的值不能改变(否则object的位置会错误)。为了保证这一点,NSDictionary会始终复制key到自己私有空间。
这个key的复制行为也是NSDictionary如何工作的基础,但是这也有一个限制:你只能使用OC对象作为NSDictionary的key,并且必须支持NSCopying协议,我们也可以从上面的方法中看到。此外,key应该是小并且高效的,以至于复制的时候不会对CPU和内存造成负担。
这意味着,NSDictionary中真的只适合将值类型的对象作为key(如简短字符串和数字)。并不适合使用自己的模型类来做对象到对象的映射。
下面针对上面所说的,字典会对key持有一份拷贝,对object强引用写一个简单的例子:
NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
{
NSString *aKey = @"akey";
NSObject *aObject = [NSObject new];
NSLog(@"存储前aObject的地址:%p",aObject);
[mDict setObject:aObject forKey:aKey];
}
NSObject *bObject = mDict.allValues.firstObject;
NSLog(@"存储后aObject的地址:%p",bObject);
NSLog(@"mDict:%@",mDict);
打印日志:
2019-09-09 18:22:11.554068+0800 NSMapTableTest[12162:517104] 存储前aObject的地址:0x600001c988c0
2019-09-09 18:22:11.554172+0800 NSMapTableTest[12162:517104] 存储后aObject的地址:0x600001c988c0
2019-09-09 18:22:11.554309+0800 NSMapTableTest[12162:517104] mDict:{
akey = "<NSObject: 0x600001c988c0>";
}
本来作用域结束之后,aKey变量指向的NSString对象(简称aKey对象)和aObject变量指向的NSObject对象(简称aObject对象)应该被自动释放,但是mDict持有一份aObject对象的强引用,所以打印日志时,mDict对象不为空,并且前后mDict的object的地址也相同。
现在有一个Teacher类表示班主任信息,包含姓名name属性和年龄age属性,另有一个Student类表示学生信息,也包含姓名name属性和年龄age属性。那么一个班包含一个班主任(Teacher对象)和n个学生(Student数组),为了统计一个班的信息,需要把班主任和学生的信息及对应关系保存下来。
Teacher类:
// Teacher.h
@interface Teacher : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
// Teacher.m
@implementation Teacher
@end
Student类:
// Student.h
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
// Student.m
@implementation Student
@end
// ViewController.m
{
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
Teacher *teacher = [[Teacher alloc] init];
teacher.name = @"teacher";
teacher.age = 30;
NSMutableArray *aArray = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 0; i < 3; i++) {
Student *student = [[Student alloc] init];
student.name = [NSString stringWithFormat:@"student%d", i];
student.age = i;
[aArray addObject:student];
}
[aDictionary setObject:aArray forKey:teacher.name];
NSLog(@"%@", aDictionary);
}
输出日志:
dictionary:{
teacher = (
"<Student: 0x60000003aa00>",
"<Student: 0x60000003a9c0>",
"<Student: 0x60000003aa80>"
);
}
这里将班主任的姓名作为key,这样会损失其他信息。如果想要将teacher对象作为key,则需要让Teacher类遵循NSCopying协议(上面有提到),而且NSDictionary/NSMutable使用hash表来实现key和value之间的映射和存储,所以作为key值的类型必须重写,也就是需要重写Teacher类的 hash 和 isEqual 方法。
// 这个方法计算该对象的hash值,hash值决定该对象在hash表中存储的位置
+ (NSUInteger)hash;
// isEqual方法通过hash值来定位对象在hash表中的位置。
- (BOOL)isEqual:(id)object;
具体代码如下:
// Teacher.h
@interface Teacher : NSObject<NSCopying>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
// Teacher.m
@implementation Teacher
- (id)copyWithZone:(NSZone *)zone
{
Teacher *teacher = [[Teacher allocWithZone:zone] init];
teacher.name = self.name;
teacher.age = self.age;
return teacher;
}
- (BOOL)isEqual:(id)object
{
// 比较hash值是否相等
return [self hash] == [object hash];
}
- (NSUInteger)hash
{
// 调用父类的hash方法,也可以自定义
return [super hash];
}
打印日志:
dictionary:{
"<Teacher: 0x600000027940>" = (
"<Student: 0x60c00022fa20>",
"<Student: 0x60c00022fa00>",
"<Student: 0x60c00022f960>"
);
}
NSMapTable浅析
NSMapTable继承自NSObject,自iOS6.0开始使用,NSMapTable是可变的。
NS_CLASS_AVAILABLE(10_5, 6_0)
@interface NSMapTable<KeyType, ObjectType> : NSObject <NSCopying, NSCoding, NSFastEnumeration>
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;
初始化方法方法中有两个参数keyOptions和valueOptions,都是NSPointerFunctionsOptions类型,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
#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || TARGET_OS_WIN32
NSPointerFunctionsZeroingWeakMemory NS_ENUM_DEPRECATED_MAC(10_5, 10_8) = (1UL << 0), // deprecated; uses GC weak read and write barriers, and dangling pointer behavior otherwise
#endif
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: 弱引用存储对象
NSPointerFunctionsCopyIn:copy存储对象
NSMapTableStrongMemory 是默认的 “memory option”。
就是说,如果NSMapTable的初始化方法为:
NSMapTable *aMapTable = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:NSPointerFunctionsStrongMemory capacity:0];
或
NSMapTable *aMapTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:NSPointerFunctionsStrongMemory];
那么就等同于NSMutableDictionary的初始化方法:
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
或
NSMutableDictionary *aDictionary = [NSMutableDictionary dictionary];
若我们使用NSMapTable来存储上面的Teacher和Student数据,使用:
NSMapTable *aMapTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];
即对key值进行弱引用,就可以不用让Teacher类遵循NSCopying协议和重新跟hash有关的两个方法,代码如下:
// Teacher.h
@interface Teacher : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
// Teacher.m
@implementation Teacher
@end
// ViewController.m
Teacher *teacher = [[Teacher alloc] init];
teacher.name = @"teacher";
teacher.age = 30;NSMutableArray *aArray = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 0; i < 3; i++) {
Student *student = [[Student alloc] init];
student.name = [NSString stringWithFormat:@"student%d", i];
student.age = i;
[aArray addObject:student];
}
NSMapTable *aMapTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];
[aMapTable setObject:aArray forKey:teacher];
NSLog(@"%@", aMapTable);
打印日志:
NSMapTable {
[10] <Teacher: 0x604000038a40> -> (
"<Student: 0x60400003c640>",
"<Student: 0x60400003c660>",
"<Student: 0x60400003c620>"
)
}
这样的方法可以快速的将NSObject对象作为key存入到“字典”中。
由于NSDictionary/NSMutableArray会强引用value,使得value的引用计数+1,加入不希望怎么做,可以用NSMapTable来实现。
NSMapTable *aMapTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory];
{
NSObject *keyObject = [[NSObject alloc] init];
NSObject *valueObject = [[NSObject alloc] init];
[aMapTable setObject:valueObject forKey:keyObject];
NSLog(@"NSMapTable:%@", aMapTable);
}
NSLog(@"NSMapTable:%@", aMapTable);
打印日志:
NSMapTable:NSMapTable {
[6] <NSObject: 0x60c00000c690> -> <NSObject: 0x60c00000c730>
}
NSMapTable:NSMapTable {
}
第一个NSLog打印出了key-value值,等到object对象指向的NSObject对象超出作用域,释放该对象,由于aMapTable弱引用object对象,aMapTable的中的key-value值会被安全的删除,第二个NSLog打印出的值为空。(如果一个NSMapTable中的key或value有一个是弱引用的,并且被释放了,那么这个对应的key-value也会被删除。)
NSMapTable与NSDictionary/NSMutableDictionary对比
NSDcitionary有一个可变类型NSMutableDictionary,NSMapTable没有可变类型,它本身就是可变的;
NSDcitionary/NSMutableDictionary中对于key和value的内存管理方法唯一,即对key进行copy,对value进行强引用,而NSMapTable没有限制;
NSDcitionary中对key值进行copy,不可改变,通常用字符串作为key值,只是key->object的映射,而NSMapTable的key是可变的对象,既可以实现key->object的映射,又可以实现object->object的映射。
参考:http://www.isaced.com/post-235.html
参考:https://yq.aliyun.com/articles/606823