NSDictionary/NSMutableArray浅析
我们在使用NSDictionary/NSMutableArray时,通常会使用NSString对象作为key,因为key必须遵循NSCopying协议,见NSMutableArray中的方法:
- (void)setObject:(ObjectType)anObject forKey:(KeyType )aKey;
在NSDictionary/NSMutableArray对象中,aKey对象被copy一份后存入,anObject对象则被强引用。来看一段代码:
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
{
NSString *aKey = @"akey";
NSObject *aObject = [[NSObject alloc] init];
[aDictionary setObject:aObject forKey:aKey];
}
NSLog(@"dictionary: %@", aDictionary);
打印日志:
dictionary: {
akey = "";
}
本来作用域结束后,aKey变量指向的NSString对象(简称aKey对象)和aObject变量指向的NSObject对象(简称aObject对象)应该被自动释放,但是aDictionary变量指向的NSMutableDictionary对象(简称aDictionary对象)持有一份aObject对象的强引用,所以打印日志时,aDictionary对象不为空。
现在有一个Teacher类表示班主任信息,包含姓名name属性和年龄age属性,另有一个Student类表示学生信息,也包含姓名name属性和年龄age属性。那么一个班包含一个班主任(Teacher对象)和n个学生(Student数组),为了统计一个班的信息,需要把班主任和学生的信息及对应关系保存下来。
// Teacher.h
@interface Teacher : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
// Teacher.m
@implementation Teacher
@end
// 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 = (
"",
"",
""
);
}
这里将班主任的姓名作为key,这样会损失其他信息。如果想要将teacher对象作为key,则需要让Teacher类遵循NSCopying协议,而且NSDictionary/NSMutable使用hash表来实现key和value之间的映射和存储,所以作为key值的类型必须重写hash和isEqual:两个方法,其中hash方法计算该对象的hash值,hash值决定该对象在hash表中存储的位置,isEqual方法通过hash值来定位对象在hash表中的位置。具体代码如下:
// Teacher.h
@interface Teacher : NSObject
@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:{
"" = (
"",
"",
""
);
}
NSMapTable浅析
NSMapTable继承自NSObject,自iOS6.0开始使用,NSMapTable是可变的。
NS_CLASS_AVAILABLE(10_5, 6_0)
@interface NSMapTable : NSObject
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 *)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存储对象
就是说,如果NSMapTable的初始化方法为:
NSMapTable *aMapTable = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:NSPointerFunctionsStrongMemory capacity:0];
或
NSMapTable *aMapTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:NSPointerFunctionsStrongMemory];
那么就等同于NSMutableDictionay的初始化方法:
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
或
NSMutableDictionary *aDictionary = [NSMutableDictionary dictionary];
若初始方法修改为
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] -> (
"",
"",
""
)
}
这样的方法可以快速的将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] ->
}
NSMapTable:NSMapTable {
}
第一个NSLog打印出了key-value值,等到object对象指向的NSObject对象超出作用域,释放该对象,由于aMapTable弱引用object对象,aMapTable的中的key-value值会被安全的删除,第二个NSLog打印出的值为空。
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的映射。
遗留的问题
笔者才疏学浅,对NSMapTable与NSDictionary的内部结构了解不是很深,不清楚key-value是通过怎么样的方式绑定起来的,假如看到这篇文章的朋友有所了解,希望可以指点一二。