内存管理

image.png

内存管理 方案

1.TaggedPointer //小对象 如:nsnumber

2.NONPOINTER_ISA // 非指针型isa 64位系统中32到40的bite放指针,为提高内存利用率,其他放内存管理相关内容

image.png

image.png

1位(indexed:0代表纯isa指针,1代表有类对象地址和内存管理内容)
2位 has_assoc 当前对象是否有关联对象(0没有1有)
3位 has_cxx_dtor 是否使用c++内容
4-36位 共33位当前对象地址
42位 weakly是否有弱引用
43位 deallocating 当前对象是否进行dealloc操作
44位 has_sidetable_rc 当引用计数达到上限后,需外挂一个散列表
45-64位 extra_rc 额外的引用计数

3.散列表SideTables 有多个Side Table结构。

image.png
  • spinlock_t 自旋锁。忙等 适用轻量访问:如引用计数加1减1
  • RefcountMap 引用计数表 通过hash表来实现 通过指针获取引用计数,插入和获取都是通过hash函数计算索引位置,避免循环遍历。提高查找效率
image.png

64位引用计数表 1 weakly,2,deallocating,3-64 RC引用计数值

  • weak_table_t 弱引用表 也是hash表 f(key) -> value 找到结构体数组的位置

  • 引用分离锁,多个table表并发访问,提高效率

image.png

image.png

快速分流 f(key)->value 通过hash函数将对象指针key计算出hash值value。快速查找到value在side tablev表 数组中的位置 下标索引

image.png

引用计数管理

alloc的实现,经过一系列调用,最终调用c函数的calloc
此时并没有设置引用计数为1,但是通过retainCount获取是1。


image.png

经过两次hash查找
1.通过当前对象指针this经过hash函数计算,获取sideTables中对应的sideTable。
2.通过当前对象指针this获取sideTable中对应的引用计数值。
3.对引用计数加1,这个宏实际是经过了一个偏移量4。


image.png

image.png

image.png

image.png

image.png

image.png

弱引用管理

image.png

image.png

image.png

自动释放池

自动释放池:
是以栈为节点通过双向链表的形式组合而成的
是和线程一一对应的


image.png

image.png

image.png

image.png

image.png

image.png

image.png

循环引用

解决NSTimer产生的循环引用
import "NSTimer+WeakTimer.h"
@interface TimerWeakObject : NSObject
@property(nonatomic,weak)id target;
@property(nonatomic,assign)SEL selector;
@property(nonatomic,weak)NSTimer * timer;
-(void)fire:(NSTimer *)timer;
@end
@implementation TimerWeakObject
-(void)fire:(NSTimer *)timer{
if (self.target) {
if ([self.target respondsToSelector:self.selector]) {
[self.target performSelector:self.selector withObject:timer.userInfo];
}
}else{
[self.timer invalidate];
}
}
@end
@implementation NSTimer (WeakTimer)
+(NSTimer *)scheduledWeakTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo{
TimerWeakObject * obj = [[TimerWeakObject alloc] init];
obj.target = aTarget;
obj.selector = aSelector;
obj.timer = [NSTimer scheduledTimerWithTimeInterval:ti target:aTarget selector:@selector(fire:) userInfo:userInfo repeats:yesOrNo];
return obj.timer;
}
@end

  • 什么是ARC:arc是由编译器llvm和runtime共同协作来实现自动引用计数的管理
  • 为什么weak指针指向的对象在被废弃之后自动置为nil:当对象被废弃之后,dealloc方法内部实现当中会调用清除弱引用的方法。该方法中会通过hash查找被废弃对象在弱引用表中的位置,来提取在弱引用表中的数组,然后通过for循环遍历把每一个弱引用都置为nil。
  • 苹果是如何实现autoreleasePoll的:autoreleasePoll是以栈为节点双向链表合成的数据结构

你可能感兴趣的:(内存管理)