此代码告诉我当前正在消耗的内存量:
-(u_int)memoryUsage {
u_int result = 0;
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
result = (info.resident_size / 1024) / 1024;
} else {
NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
}
return result;
}
为了测试这一点,我写了这个:
NSLog(@"USAGE: %u mb",[self memoryUsage]);
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 1000000; ++i) {
[array addObject:@"Hello!"];
}
NSLog(@"USAGE: %u mb",[self memoryUsage]);
[array removeAllObjects];
NSLog(@"USAGE: %u mb",[self memoryUsage]);
输出是:
5 mb
10 mb
10 mb
在创建一个包含 1000000 个字符串的数组后,内存增加了 5 mb。但是清理之后,内存使用没有被修改。
这是为什么?