上篇文章讲了各类锁的使用和读写锁的应用, 看完本文章你将了解到c++
- DisplayLink和timer的使用和原理
- 内存分配和内存管理
- 自动释放池原理
- weak指针原理和释放时机
- 引用计数原理
CADisplayLink
是将任务添加到runloop
中,loop
每次循环便会调用target
的selector
,使用这个也能监测卡顿问题。首先介绍下API
git
+ (CADisplayLink *)displayLinkWithTarget:(id)target selector:(SEL)sel;
//runloop没循环一圈都会调用
- (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;
//从runloop中删除
- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;
//取消
- (void)invalidate;
复制代码
咱们在一个须要push
的VC
中运行来观察声明周期github
@property (nonatomic,strong) CADisplayLink *link;
//初始化
self.link = [FYDisplayLink displayLinkWithTarget:self selector:@selector(test)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
@synchronized (self) {
NSLog(@"FPS:%d",fps);
fps = 0;
}
});
dispatch_resume(timer);
//全局变量
dispatch_source_t timer;
static int fps;
- (void)test{
@synchronized (self) {
fps += 1;
}
}
- (void)dealloc{
[self.link invalidate];
NSLog(@"%s",__func__);
}
//log
2019-07-30 17:44:37.217781+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:38.212477+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:39.706000+0800 day17-定时器[29637:6504821] FPS:89
2019-07-30 17:44:40.706064+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:41.705589+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:42.706268+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:43.705942+0800 day17-定时器[29637:6504821] FPS:60
2019-07-30 17:44:44.705792+0800 day17-定时器[29637:6504821] FPS:60
复制代码
初始化以后,对fps
使用了简单版本的读写锁,能够看到fps
基本稳定在60左右,点击按钮返回以后,link
和VC
并无正常销毁。咱们分析一下,VC(self)
->link
->target(self)
,致使了死循环,释放的时候,没法释放self
和link
,那么咱们改动一下link
->target(self)
中的强引用,改为弱引用,代码改为下面的算法
@interface FYTimerTarget : NSObject
@property (nonatomic,weak) id target;
@end
@implementation FYTimerTarget
-(id)forwardingTargetForSelector:(SEL)aSelector{
return self.target;
}
- (void)dealloc{
NSLog(@"%s",__func__);
}
@end
FYProxy *proxy=[FYProxy proxyWithTarget:self];
self.link = [FYDisplayLink displayLinkWithTarget:self selector:@selector(test)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
- (void)test{
NSLog(@"%s",__func__);
}
//log
2019-07-30 17:59:04.339934 -[ViewController test]
2019-07-30 17:59:04.356292 -[ViewController test]
2019-07-30 17:59:04.371428 -[FYTimerTarget dealloc]
2019-07-30 17:59:04.371634 -[ViewController dealloc]
复制代码
FYTimerTarget
对target
进行了弱引用,self
对FYTimerTarget
进行强引用,在销毁了的时候,先释放self
,而后检查self
的FYTimerTarget
,FYTimerTarget
只有一个参数weak
属性,能够直接释放,释放完FYTimerTarget
,而后释放self(VC)
,最终能够正常。编程
使用NSTimer
的时候,timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo
会对aTarget
进行强引用,因此咱们对这个aTarget
进行一个简单的封装数组
@interface FYProxy : NSProxy
@property (nonatomic,weak) id target;
+(instancetype)proxyWithTarget:(id)target;
@end
@implementation FYProxy
- (void)dealloc{
NSLog(@"%s",__func__);
}
+ (instancetype)proxyWithTarget:(id)target{
FYProxy *obj=[FYProxy alloc];
obj.target = target;
return obj;
}
//转发
- (void)forwardInvocation:(NSInvocation *)invocation{
[invocation invokeWithTarget:self.target];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
return [self.target methodSignatureForSelector:sel];
}
@end
复制代码
FYProxy
是继承NSProxy
,而NSProxy
不是继承NSObject
的,而是另一种基类,不会走objc_msgSend()
的三大步骤,当找不到函数的时候直接执行- (void)forwardInvocation:(NSInvocation *)invocation
,和- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
直接进入消息转发阶段。或者将继承关系改为FYTimerTarget : NSObject
,这样子target
找不到的函数仍是会走消息转发的三大步骤,咱们再FYTimerTarget
添加消息动态解析性能优化
-(id)forwardingTargetForSelector:(SEL)aSelector{
return self.target;
}
复制代码
这样子target
的aSelector
转发给了self.target
处理,成功弱引用了self
和函数的转发处理。bash
FYTimerTarget *obj =[FYTimerTarget new];
obj.target = self;
self.timer = [NSTimer timerWithTimeInterval:1.0f
target:obj
selector:@selector(test)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
[self.timer setFireDate:[NSDate distantPast]];
//log
2019-07-30 18:03:08.723433+0800 day17-定时器[30877:6556631] -[ViewController test]
2019-07-30 18:03:09.722611+0800 day17-定时器[30877:6556631] -[ViewController test]
2019-07-30 18:03:09.847540+0800 day17-定时器[30877:6556631] -[FYTimerTarget dealloc]
2019-07-30 18:03:09.847677+0800 day17-定时器[30877:6556631] -[ViewController dealloc]
复制代码
或者使用timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
,而后外部使用__weak self
调用函数,也不会产生循环引用。 使用block
的状况,释放正常。多线程
self.timer=[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"123");
}];
//log
2019-07-30 18:08:24.678789+0800 day17-定时器[31126:6566530] 123
2019-07-30 18:08:25.659127+0800 day17-定时器[31126:6566530] 123
2019-07-30 18:08:26.107643+0800 day17-定时器[31126:6566530] -[ViewController dealloc]
复制代码
因为link
和timer
是添加到runloop
中使用的,每次一个循环则访问timer
或者link
,而后执行对应的函数,在时间上有相对少量偏差的,每此循环,要刷新UI(在主线程),要执行其余函数,要处理系统端口事件,要处理其余的计算。。。总的来讲,偏差仍是有的。并发
GCD
中的dispatch_source_t
的定时器是基于内核的,时间偏差相对较少。
//timer 须要强引用 或者设置成全局变量
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
//设置
dispatch_source_set_event_handler(timer, ^{
//code 定时器执行的代码
});
//开始定时器
dispatch_resume(timer);
复制代码
或者使用函数dispatch_source_set_event_handler_f(timer, function_t);
dispatch_source_set_event_handler_f(timer, function_t);
void function_t(void * p){
//code here
}
复制代码
业务常用定时器的话,仍是封装一个简单的功能比较好,封装首先从需求开始分析,咱们使用定时器经常使用的参数都哪些?须要哪些功能?
首先须要开始的时间,而后执行的频率,执行的任务(函数或block),是否重复执行,这些都是须要的。 先定义一个函数
+ (NSString *)exeTask:(dispatch_block_t)block
start:(NSTimeInterval)time
interval:(NSTimeInterval)interval
repeat:(BOOL)repeat
async:(BOOL)async;
+ (NSString *)exeTask:(id)target
sel:(SEL)aciton
start:(NSTimeInterval)time
interval:(NSTimeInterval)interval
repeat:(BOOL)repeat
async:(BOOL)async;
//取消
+ (void)exeCancelTask:(NSString *)key;
复制代码
而后将刚才写的拿过来,增长了一些判断。有任务的时候才会执行,不然直接返回nil
,当循环的时候,须要间隔大于0,不然返回,同步或异步,就或者主队列或者异步队列,而后用生成的key
,timer
为value
存储到全局变量中,在取消的时候直接用key
取出timer
取消,这里使用了信号量,限制单线程操做。在存储和取出(取消timer)的时候进行限制,提升其余代码执行的效率。
+ (NSString *)exeTask:(dispatch_block_t)block start:(NSTimeInterval)time interval:(NSTimeInterval)interval repeat:(BOOL)repeat async:(BOOL)async{
if (block == nil) {
return nil;
}
if (repeat && interval <= 0) {
return nil;
}
NSString *name =[NSString stringWithFormat:@"%d",i];
//主队列
dispatch_queue_t queue = dispatch_get_main_queue();
if (async) {
queue = dispatch_queue_create("async.com", DISPATCH_QUEUE_CONCURRENT);
}
//建立定时器
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置启动时间
dispatch_source_set_timer(_timer,
dispatch_time(DISPATCH_TIME_NOW, time*NSEC_PER_SEC), interval*NSEC_PER_SEC, 0);
//设定回调
dispatch_source_set_event_handler(_timer, ^{
block();
if (repeat == NO) {
dispatch_source_cancel(_timer);
}
});
//启动定时器
dispatch_resume(_timer);
//存放到字典
if (name.length && _timer) {
dispatch_semaphore_wait(samephore, DISPATCH_TIME_FOREVER);
timers[name] = _timer;
dispatch_semaphore_signal(samephore);
}
return name;
}
+ (NSString *)exeTask:(id)target
sel:(SEL)aciton
start:(NSTimeInterval)time
interval:(NSTimeInterval)interval
repeat:(BOOL)repeat
async:(BOOL)async{
if (target == nil || aciton == NULL) {
return nil;
}
if (repeat && interval <= 0) {
return nil;
}
NSString *name =[NSString stringWithFormat:@"%d",i];
//主队列
dispatch_queue_t queue = dispatch_get_main_queue();
if (async) {
queue = dispatch_queue_create("async.com", DISPATCH_QUEUE_CONCURRENT);
}
//建立定时器
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置启动时间
dispatch_source_set_timer(_timer,
dispatch_time(DISPATCH_TIME_NOW, time*NSEC_PER_SEC), interval*NSEC_PER_SEC, 0);
//设定回调
dispatch_source_set_event_handler(_timer, ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
//这里是会报警告的代码
if ([target respondsToSelector:aciton]) {
[target performSelector:aciton];
}
#pragma clang diagnostic pop
if (repeat == NO) {
dispatch_source_cancel(_timer);
}
});
//启动定时器
dispatch_resume(_timer);
//存放到字典
if (name.length && _timer) {
dispatch_semaphore_wait(samephore, DISPATCH_TIME_FOREVER);
timers[name] = _timer;
dispatch_semaphore_signal(samephore);
}
return name;
}
+ (void)exeCancelTask:(NSString *)key{
if (key.length == 0) {
return;
}
dispatch_semaphore_wait(samephore, DISPATCH_TIME_FOREVER);
if ([timers.allKeys containsObject:key]) {
dispatch_source_cancel(timers[key]);
[timers removeObjectForKey:key];
}
dispatch_semaphore_signal(samephore);
}
复制代码
用的时候很简单
key = [FYTimer exeTask:^{
NSLog(@"123");
} start:1
interval:1
repeat:YES
async:NO];
复制代码
或者
key = [FYTimer exeTask:self sel:@selector(test) start:0 interval:1 repeat:YES async:YES];
复制代码
取消执行的时候
[FYTimer exeCancelTask:key];
复制代码
测试封装的定时器
- (void)viewDidLoad {
[super viewDidLoad];
key = [FYTimer exeTask:self sel:@selector(test) start:0 interval:1 repeat:YES async:YES];
}
-(void)test{
NSLog(@"%@",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[FYTimer exeCancelTask:key];
}
//log
2019-07-30 21:16:48.639486+0800 day17-定时器2[48817:1300897] <NSThread: 0x6000010ec000>{number = 4, name = (null)}
2019-07-30 21:16:49.640177+0800 day17-定时器2[48817:1300897] <NSThread: 0x6000010ec000>{number = 4, name = (null)}
2019-07-30 21:16:50.639668+0800 day17-定时器2[48817:1300897] <NSThread: 0x6000010ec000>{number = 4, name = (null)}
2019-07-30 21:16:51.639590+0800 day17-定时器2[48817:1300897] <NSThread: 0x6000010ec000>{number = 4, name = (null)}
2019-07-30 21:16:52.156004+0800 day17-定时器2[48817:1300845] -[ViewController touchesBegan:withEvent:]
复制代码
在点击VC
的时候进行取消操做,timer
中止。
NSProxy
实际上是除了NSObject
的另一个基类,方法比较少,当找不到方法的时候执行消息转发阶段(由于没有父类),调用函数的流程更短,性能则更好。
问题:ret1
和ret2
分别是多少?
ViewController *vc1 =[[ViewController alloc]init];
FYProxy *pro1 =[FYProxy proxyWithTarget:vc1];
FYTimerTarget *tar =[FYTimerTarget proxyWithTarget:vc1];
BOOL ret1 = [pro1 isKindOfClass:ViewController.class];
BOOL ret2 = [tar isKindOfClass:ViewController.class];
NSLog(@"%d %d",ret1,ret2);
复制代码
咱们来分析一下,-(bool)isKindOfClass:(cls)
对象函数是判断该对象是否的cls
的子类或者该类的实例,这点无可置疑,那么ret1
应该是0
,ret2
应该也是0
首先看FYProxy
的实现,forwardInvocation
和methodSignatureForSelector
,在没有该函数的时候进行消息转发,转发对象是self.target
,在该例子中isKindOfClass
不存在与FYProxy
,因此讲该函数转发给了VC
,则BOOL ret1 = [pro1 isKindOfClass:ViewController.class];
至关于BOOL ret1 = [ViewController.class isKindOfClass:ViewController.class];
,因此答案是1
而后ret2
是0,tar
是继承于NSObject
的,自己有-(bool)isKindOfClass:(cls)
函数,因此答案是0。
答案是:ret1
是1
,ret2
是0
。
内存分为保留段、数据段、堆(↓)、栈(↑)、内核区。
数据段包括
栈:函数调用开销、好比局部变量,分配的内存空间地址愈来愈小。
堆:经过alloc、malloc、calloc等动态分配的空间,分配的空间地址愈来愈大。
验证:
int a = 10;
int b ;
int main(int argc, char * argv[]) {
@autoreleasepool {
static int c = 20;
static int d;
int e = 10;
int f;
NSString * str = @"123";
NSObject *obj =[[NSObject alloc]init];
NSLog(@"\na:%p \nb:%p \nc:%p \nd:%p \ne:%p \nf:%p \nobj:%p\n str:%p",&a,&b,&c,&d,&e,&f,obj,str);
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
//log
a:0x1063e0d98
b:0x1063e0e64
c:0x1063e0d9c
d:0x1063e0e60
e:0x7ffee9820efc
f:0x7ffee9820ef8
obj:0x6000013541a0
str:0x1063e0068
复制代码
从64bit开始,iOS引入Tagged Pointer
技术,用于优化NSNumber、NSDate、NSString
等小对象的存储,在没有使用以前,他们须要动态分配内存,维护计数,使用Tagged Pointer
以后,NSNumber
指针里面的数据变成了Tag+Data
,也就是将数值直接存储在了指针中,只有当指针不够存储数据时,才会动态分配内存的方式来存储数据,并且objc_msgSend()
可以识别出Tagged Pointer
,好比NSNumber
的intValue
方法,直接从指针提取数据,节省了之前的调用的开销。 在iOS中,最高位是1(第64bit),在Mac中,最低有效位是1。 在runtime
源码中objc-internal.h 370行
判断是否使用了优化技术
static inline void * _Nonnull
_objc_encodeTaggedPointer(uintptr_t ptr)
{
return (void *)(objc_debug_taggedpointer_obfuscator ^ ptr);
}
复制代码
咱们拿来这个能够判断对象是否使用了优化技术。
咱们使用几个NSNumber
的大小数字来验证
#if (TARGET_OS_OSX || TARGET_OS_IOSMAC) && __x86_64__ //mac开发
// 64-bit Mac - tag bit is LSB
# define OBJC_MSB_TAGGED_POINTERS 0
#else
// Everything else - tag bit is MSB
# define OBJC_MSB_TAGGED_POINTERS 1//iOS开发
#endif
#if OBJC_MSB_TAGGED_POINTERS
# define _OBJC_TAG_MASK (1UL<<63)
#else
# define _OBJC_TAG_MASK 1UL
#endif
bool objc_isTaggedPointer(const void * _Nullable ptr)
{
return ((uintptr_t)ptr & _OBJC_TAG_MASK) == _OBJC_TAG_MASK;
}
int main(int argc, char * argv[]) {
@autoreleasepool {
NSNumber *n1 = @2;
NSNumber *n2 = @3;
NSNumber *n3 = @(4);
NSNumber *n4 = @(0x4fffffffff);
NSLog(@"\n%p \n%p \n%p \n%p",n1,n2,n3,n4);
BOOL n1_tag = objc_isTaggedPointer((__bridge const void * _Nullable)(n1));
BOOL n2_tag = objc_isTaggedPointer((__bridge const void * _Nullable)(n2));
BOOL n3_tag = objc_isTaggedPointer((__bridge const void * _Nullable)(n3));
BOOL n4_tag = objc_isTaggedPointer((__bridge const void * _Nullable)(n4));
NSLog(@"\nn1:%d \nn2:%d \nn3:%d \nn4:%d ",n1_tag,n2_tag,n3_tag,n4_tag);
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
//log
0xbf4071e2657ccb95
0xbf4071e2657ccb85
0xbf4071e2657ccbf5
0xbf40751d9a833444
2019-07-30 21:55:52.626317+0800 day17-TaggedPointer[49770:1328036]
n1:1
n2:1
n3:1
n4:0
复制代码
能够看到n1 n2 n3
是通过优化的,而n4
是大数字,指针容不下该数值,不能优化。
看下面一道题,运行test1
和test2
会出现什么问题?
- (void)test1{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (NSInteger i = 0; i < 1000; i ++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abc"];
});
}
}
- (void)test2{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (NSInteger i = 0; i < 1000; i ++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abcsefafaefafafaefe"];
});
}
}
复制代码
咱们先不运行,先分析一下。
首先全局队列异步添加任务会出现多线程并发问题,在并发的时候进行写操做会出现资源竞争问题,另一个小字符串会出现指针优化问题,小字符串和大字符串切换致使_name
结构变化,多线程同时写入和读会致使访问坏内存问题,咱们来运行一下
Thread: EXC_BAD_ACCESS(code = 1)
复制代码
直接在子线程崩溃了,崩溃函数是objc_release
。符合咱们的猜测。
验证NSString Tagged Pointer
- (void)test{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (NSInteger i = 0; i < 1; i ++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abc"];
NSLog(@"test1 class:%@",self.name.class);
});
}
}
- (void)test2{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (NSInteger i = 0; i < 1; i ++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abcsefafaefafafaefe"];
NSLog(@"test2 class:%@",self.name.class);
});
}
}
//log
test1 class:NSTaggedPointerString
test2 class:__NSCFString
复制代码
能够看到NSString Tagged Pointer
在小字符串的时候类是NSTaggedPointerString
,通过优化的类,大字符串的类是__NSCFString
,
拷贝分为浅拷贝和深拷贝,浅拷贝只是引用计数+1,深拷贝是拷贝了一个对象,和以前的 互不影响, 引用计数互不影响。
拷贝目的:产生一个副本对象,跟源对象互不影响 修改源对象,不会影响到副本对象 修改副本对象,不会影响源对象
iOS提供了2中拷贝方法
void test1(){
NSString *str = @"strstrstrstr";
NSMutableString *mut1 =[str mutableCopy];
[mut1 appendFormat:@"123"];
NSString *str2 = [str copy];
NSLog(@"%p %p %p",str,mut1,str2);
}
//log
str:0x100001040
mut1:0x1007385f0
str2:0x100001040
复制代码
能够看到str
和str2
地址同样,没有从新复制出来一份,mut1
地址和str
不一致,是深拷贝,从新拷贝了一份。
咱们把字符串换成其余经常使用的数组
void test2(){
NSArray *array = @[@"123",@"123",@"123",@"123",@"123",@"123",@"123"];
NSMutableArray *mut =[array mutableCopy];
NSString *array2 = [array copy];
NSLog(@"\n%p \n%p\n%p",array,mut,array2);
}
//log
0x102840800
0x1028408a0
0x102840800
void test3(){
NSArray *array = [@[@"123",@"123",@"123",@"123",@"123",@"123",@"123"] mutableCopy];
NSMutableArray *mut =[array mutableCopy];
NSString *array2 = [array copy];
NSLog(@"\n%p \n%p\n%p",array,mut,array2);
}
//log
0x102808720
0x1028088a0
0x1028089a0
复制代码
从上面能够总结看出来,不变数组拷贝出来不变数组,地址不改变,拷贝出来可变数组地址改变,可变数组拷贝出来不可变数组和可变数组,地址会改变。
咱们再换成其余的经常使用的字典
void test4(){
NSDictionary *item = @{@"key":@"value"};
NSMutableDictionary *mut =[item mutableCopy];
NSDictionary *item2 = [item copy];
NSLog(@"\n%p \n%p\n%p",item,mut,item2);
}
//log
0x1007789c0
0x100779190
0x1007789c0
void test5(){
NSDictionary *item = [@{@"key":@"value"}mutableCopy];
NSMutableDictionary *mut =[item mutableCopy];
NSDictionary *item2 = [item copy];
NSLog(@"\n%p \n%p\n%p",item,mut,item2);
}
//log
0x1007041d0
0x1007042b0
0x1007043a0
复制代码
从上面能够总结看出来,不变字典拷贝出来不变字典,地址不改变,拷贝出来可变字典地址改变,可变字典拷贝出来不可变字典和可变字典,地址会改变。
由这几个看出来,总结出来下表
类型 | copy | mutableCopy |
---|---|---|
NSString | 浅拷贝 | 深拷贝 |
NSMutableString | 浅拷贝 | 深拷贝 |
NSArray | 浅拷贝 | 深拷贝 |
NSMutableArray | 深拷贝 | 深拷贝 |
NSDictionary | 浅拷贝 | 深拷贝 |
NSMutableDictionary | 深拷贝 | 深拷贝 |
自定义的对象使用copy呢?系统的已经实现了,咱们自定义的须要本身去实现,自定义的类继承NSCopying
@protocol NSCopying
- (id)copyWithZone:(nullable NSZone *)zone;
@end
@protocol NSMutableCopying
- (id)mutableCopyWithZone:(nullable NSZone *)zone;
@end
复制代码
看到NSCopying
和NSMutableCopying
这两个协议,对于自定义的可变对象,其实没什么意义,原本自定义的对象的属性,基本都是可变的,因此只须要实现NSCopying
协议就行了。
@interface FYPerson : NSObject
@property (nonatomic,assign) int age;
@property (nonatomic,assign) int level;
@end
@interface FYPerson()<NSCopying>
@end
@implementation FYPerson
-(instancetype)copyWithZone:(NSZone *)zone{
FYPerson *p=[[FYPerson alloc]init];
p.age = self.age;
p.level = self.level;
return p;
}
@end
FYPerson *p =[[FYPerson alloc]init];
p.age = 10;
p.level = 11;
FYPerson *p2 =[p copy];
NSLog(@"%d %d",p2.age,p2.level);
//log
10 11
复制代码
本身实现了NSCoping
协议完成了对对象的深拷贝,成功将对象的属性复制过去了,当属性多了怎么办?咱们能够利用runtime
实现一个一劳永逸的方案。
而后将copyWithZone
利用runtime
遍历全部的成员变量,将全部的变量都赋值,当变量多的时候,这里也不用修改。
@implementation NSObject (add)
-(instancetype)copyWithZone:(NSZone *)zone{
Class cls = [self class];
NSObject * p=[cls new];
//成员变量个数
unsigned int count;
//赋值成员变量数组
Ivar *ivars = class_copyIvarList(self.class, &count);
//遍历数组
for (int i = 0; i < count; i ++) {
Ivar var = ivars[i];
//获取成员变量名字
const char * name = ivar_getName(var);
if (name != nil) {
NSString *v = [NSString stringWithUTF8String:name];
id value = [self valueForKey:v];
//给新的对象赋值
if (value != NULL) {
[p setValue:value forKey:v];
}
}
}
free(ivars);
return p;
}
@end
FYPerson *p =[[FYPerson alloc]init];
p.age = 10;
p.level = 11;
p.name = @"xiaowang";
FYPerson *p2 =[p copy];
NSLog(@"%d %d %@",p2.age,p2.level,p2.name);
//log
10
11
xiaowang
复制代码
根据启动顺序,类别的方法在类的方法加载后边,类别中的方法会覆盖类的方法,因此 在基类NSObject
在类别中重写了-(instancetype)copyWithZone:(NSZone *)zone
方法,子类就不用重写了。达成了一劳永逸的方案。
摘自百度百科
引用计数是计算机编程语言中的一种内存管理技术,是指将资源(能够是对象、内存或磁盘空间等等)的被引用次数保存起来,当被引用次数变为零时就将其释放的过程。使用引用计数技术能够实现自动资源管理的目的。同时引用计数还能够指使用引用计数技术回收未使用资源的垃圾回收算法
在iOS中,使用引用计数来管理OC
对象内存,一个新建立的OC对象的引用计数默认是1,当引用计数减为0,OC
对象就会销毁,释放其余内存空间,调用retain
会让OC
对象的引用计数+1,调用release
会让OC
对象的引用计数-1。 当调用alloc、new、copy、mutableCopy
方法返回一个对象,在不须要这个对象时,要调用release
或者autorelease
来释放它,想拥有某个对象,就让他的引用计数+1,再也不拥有某个对象,就让他引用计数-1.
在MRC中咱们常常都是这样子使用的
FYPerson *p=[[FYPerson alloc]init];
FYPerson *p2 =[p retain];
//code here
[p release];
[p2 release];
复制代码
可是在ARC中是系统帮咱们作了自动引用计数,不用开发者作不少繁琐的事情了,咱们就探究下引用计数是怎么实现的。
引用计数存储在isa
指针中的extra_rc
,存储值大于这个范围的时候,则bits.has_sidetable_rc=1
而后将剩余的RetainCount
存储到全局的table
,key
是self
对应的值。
Retain
的runtime
源码查找函数路径objc_object::retain()
->objc_object::rootRetain()
->objc_object::rootRetain(bool, bool)
//大几率x==1 提升读取指令的效率
#define fastpath(x) (__builtin_expect(bool(x), 1))
//大几率x==0 提升读取指令的效率
#define slowpath(x) (__builtin_expect(bool(x), 0))
//引用计数+1
//tryRetain 尝试+1
//handleOverflow 是否覆盖
ALWAYS_INLINE id objc_object::rootRetain(bool tryRetain, bool handleOverflow)
{
//优化的指针 返回this
if (isTaggedPointer()) return (id)this;
bool sideTableLocked = false;
bool transcribeToSideTable = false;
isa_t oldisa;
isa_t newisa;
do {
transcribeToSideTable = false;
//old bits
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
//使用联合体技术
if (slowpath(!newisa.nonpointer)) {
ClearExclusive(&isa.bits);//nothing
if (!tryRetain && sideTableLocked) sidetable_unlock();//解锁
if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
else return sidetable_retain();////sidetable 引用计数+1
}
// don't check newisa.fast_rr; we already called any RR overrides //不尝试retain 和 正在销毁 什么都不作 返回 nil if (slowpath(tryRetain && newisa.deallocating)) { ClearExclusive(&isa.bits); if (!tryRetain && sideTableLocked) sidetable_unlock(); return nil; } uintptr_t carry; //引用计数+1 (bits.extra_rc++;) newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry); // extra_rc++ if (slowpath(carry)) { // newisa.extra_rc++ 溢出处理 if (!handleOverflow) { ClearExclusive(&isa.bits); return rootRetain_overflow(tryRetain); } //为拷贝到side table 作准备 if (!tryRetain && !sideTableLocked) sidetable_lock(); sideTableLocked = true; transcribeToSideTable = true; newisa.extra_rc = RC_HALF; newisa.has_sidetable_rc = true; } } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits))); if (slowpath(transcribeToSideTable)) { //拷贝 平外一半的 引用计数到 side table sidetable_addExtraRC_nolock(RC_HALF); } if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock(); return (id)this; } //sidetable 引用计数+1 id objc_object::sidetable_retain() { #if SUPPORT_NONPOINTER_ISA assert(!isa.nonpointer); #endif //取出table key=this SideTable& table = SideTables()[this]; table.lock(); size_t& refcntStorage = table.refcnts[this]; if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) { refcntStorage += SIDE_TABLE_RC_ONE; } table.unlock(); return (id)this; } 复制代码
引用计数+1,判断了须要是指针没有优化和isa
有没有使用的联合体技术,而后将判断是否溢出,溢出的话,将extra_rc
的值复制到side table
中,设置参数isa->has_sidetable_rc=true
。
引用计数-1,在runtime
源码中查找路径是objc_object::release()
->objc_object::rootRelease()
->objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
,咱们进入到函数内部
ALWAYS_INLINE bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
{
if (isTaggedPointer()) return false;//指针优化的不存在计数器
bool sideTableLocked = false;
isa_t oldisa;
isa_t newisa;
retry:
do {//isa
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
if (slowpath(!newisa.nonpointer)) {
ClearExclusive(&isa.bits);
if (sideTableLocked) sidetable_unlock();
//side table -1
return sidetable_release(performDealloc);
}
uintptr_t carry;
newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry); // extra_rc--
if (slowpath(carry)) {
// don't ClearExclusive() goto underflow; } } while (slowpath(!StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits))); if (slowpath(sideTableLocked)) sidetable_unlock(); return false; underflow: newisa = oldisa; if (slowpath(newisa.has_sidetable_rc)) { if (!handleUnderflow) { ClearExclusive(&isa.bits); return rootRelease_underflow(performDealloc); } if (!sideTableLocked) { ClearExclusive(&isa.bits); sidetable_lock(); sideTableLocked = true; goto retry; } //side table 引用计数-1 size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF); if (borrowed > 0) { newisa.extra_rc = borrowed - 1; // redo the original decrement too bool stored = StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits); if (!stored) { isa_t oldisa2 = LoadExclusive(&isa.bits); isa_t newisa2 = oldisa2; if (newisa2.nonpointer) { uintptr_t overflow; newisa2.bits = addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow); if (!overflow) { stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits, newisa2.bits); } } } if (!stored) { // Inline update failed. // Put the retains back in the side table. sidetable_addExtraRC_nolock(borrowed); goto retry; } sidetable_unlock(); return false; } else { // Side table is empty after all. Fall-through to the dealloc path. } } //真正的销毁 if (slowpath(newisa.deallocating)) { ClearExclusive(&isa.bits); if (sideTableLocked) sidetable_unlock(); return overrelease_error(); // does not actually return } //设置正在销毁 newisa.deallocating = true; if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry; if (slowpath(sideTableLocked)) sidetable_unlock(); __sync_synchronize(); if (performDealloc) { //销毁 ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc); } return true; } 复制代码
看了上边了解到引用计数分两部分,extra_rc
和side table
,探究一下 rootRetainCount()
的实现
inline uintptr_t objc_object::rootRetainCount()
{
//优化指针 直接返回
if (isTaggedPointer()) return (uintptr_t)this;
//没优化则 到SideTable 读取
sidetable_lock();
//isa指针
isa_t bits = LoadExclusive(&isa.bits);
ClearExclusive(&isa.bits);//啥都没作
if (bits.nonpointer) {//使用联合体存储更多的数据
uintptr_t rc = 1 + bits.extra_rc;//计数数量
if (bits.has_sidetable_rc) {//当大过于 联合体存储的值 则另外在SideTable读取数据
//读取table的值 相加
rc += sidetable_getExtraRC_nolock();
}
sidetable_unlock();
return rc;
}
sidetable_unlock();
//在sidetable 中存储的count
return sidetable_retainCount();
}
复制代码
当是存储小数据的时候,指针优化,则直接返回self
,大数据的话,则table
加锁, class
优化的以后使用联合体存储更多的数据,class
没有优化则直接去sizedable
读取数据。 优化了则在sidetable_getExtraRC_nolock()
读取数据
//使用联合体
size_t objc_object::sidetable_getExtraRC_nolock()
{
//不是联合体技术 则报错
assert(isa.nonpointer);
//key是 this,存储了每一个对象的table
SideTable& table = SideTables()[this];
//找到 it 不然返回0
RefcountMap::iterator it = table.refcnts.find(this);
if (it == table.refcnts.end()) return 0;
else return it->second >> SIDE_TABLE_RC_SHIFT;
}
复制代码
没有优化的是直接读取
//未使用联合体的状况,
uintptr_t objc_object::sidetable_retainCount()
{//没有联合体存储的计数器则直接在table中取出来
SideTable& table = SideTables()[this];
size_t refcnt_result = 1;
table.lock();
RefcountMap::iterator it = table.refcnts.find(this);
if (it != table.refcnts.end()) {
refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
}
table.unlock();
return refcnt_result;
}
复制代码
当一个对象要销毁的时候会调用dealloc
,调用轨迹是dealloc
->_objc_rootDealloc
->object_dispose
->objc_destructInstance
->free
咱们进入到objc_destructInstance
内部
void *objc_destructInstance(id obj)
{
if (obj) {
// Read all of the flags at once for performance.
//c++析构函数
bool cxx = obj->hasCxxDtor();
//关联函数
bool assoc = obj->hasAssociatedObjects();
// This order is important.
if (cxx) object_cxxDestruct(obj);
if (assoc) _object_remove_assocations(obj);
obj->clearDeallocating();
}
return obj;
}
复制代码
销毁了c++析构函数和关联函数最后进入到clearDeallocating
,咱们进入到函数内部
//正在清除side table 和weakly referenced
inline void
objc_object::clearDeallocating()
{
if (slowpath(!isa.nonpointer)) {
// Slow path for raw pointer isa.
//释放weak
sidetable_clearDeallocating();
}
else if (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) {
// Slow path for non-pointer isa with weak refs and/or side table data.
//释放weak 和引用计数
clearDeallocating_slow();
}
assert(!sidetable_present());
}
复制代码
最终调用了sidetable_clearDeallocating
和clearDeallocating_slow
实现销毁weak
和引用计数side table
。
NEVER_INLINE void
objc_object::clearDeallocating_slow()
{
assert(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
SideTable& table = SideTables()[this];
table.lock();
//清除weak
if (isa.weakly_referenced) {
//table.weak_table 弱引用表
weak_clear_no_lock(&table.weak_table, (id)this);
}
//引用计数
if (isa.has_sidetable_rc) {
//擦除 this
table.refcnts.erase(this);
}
table.unlock();
}
复制代码
其实weak
修饰的对象会存储在全局的SideTable
,当对象销毁的时候会在SideTable
进行查找,时候有weak
对象,有的话则进行销毁。
Autoreleasepool
中文名自动释放池,里边装着一些变量,当池子不须要(销毁)的时候,release
里边的对象(引用计数-1)。 咱们将下边的代码转化成c++
@autoreleasepool {
FYPerson *p = [[FYPerson alloc]init];
}
复制代码
使用xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc -f main.m
转成c++
/* @autoreleasepool */ {
__AtAutoreleasePool __autoreleasepool;
FYPerson *p = ((FYPerson *(*)(id, SEL))(void *)objc_msgSend)((id)((FYPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("FYPerson"), sel_registerName("alloc")), sel_registerName("init"));
}
复制代码
__AtAutoreleasePool
是一个结构体
struct __AtAutoreleasePool {
__AtAutoreleasePool() {//构造函数 生成结构体变量的时候调用
atautoreleasepoolobj = objc_autoreleasePoolPush();
}
~__AtAutoreleasePool() {//析构函数 销毁的时候调用
objc_autoreleasePoolPop(atautoreleasepoolobj);
}
void * atautoreleasepoolobj;
};
复制代码
而后将上边的代码和c++整合到一块儿就是这样子
{
__AtAutoreleasePool pool = objc_autoreleasePoolPush();
FYPerson *p = [[FYPerson alloc]init];
objc_autoreleasePoolPop(pool)
}
复制代码
在进入大括号生成一个释放池,离开大括号则释放释放池,咱们再看一下释放函数是怎么工做的,在runtime
源码中NSObject.mm 1848 行
void objc_autoreleasePoolPop(void *ctxt)
{
AutoreleasePoolPage::pop(ctxt);
}
复制代码
pop
实现了AutoreleasePoolPage
中的对象的释放,想了解怎么释放的能够研究下源码runtime NSObject.mm 1063行
。
其实AutoreleasePool
是AutoreleasePoolPage
来管理的,AutoreleasePoolpage
结构以下
class AutoreleasePoolPage {
magic_t const magic;
id *next;//下一个存放aotoreleass对象的地址
pthread_t const thread;//线程
AutoreleasePoolPage * const parent; //父节点
AutoreleasePoolPage *child;//子节点
uint32_t const depth;//深度
uint32_t hiwat;
}
复制代码
AutoreleasePoolPage
在初始化在autoreleaseNewPage
申请了4096
字节除了本身变量的空间,AutoreleasePoolPage
是一个C++
实现的类
id *next
指向了栈顶最新add
进来的autorelease
对象的下一个位置AutoreleasePoolPage
的空间被占满时,会新建一个AutoreleasePoolPage
对象,链接链表,后来的autorelease
对象在新的page
加入AutoreleasePoolPage
每一个对象会开辟4096字节内存(也就是虚拟内存一页的大小),除了上面的实例变量所占空间,剩下的空间所有用来储存autorelease
对象的地址AutoreleasePool
是按线程一一对应的(结构中的thread
指针指向当前线程)AutoreleasePool
并无单独的结构,而是由若干个AutoreleasePoolPage
以双向链表的形式组合而成(分别对应结构中的parent
指针和child
指针)其余的都是自动释放池的其余对象的指针,咱们使用_objc_autoreleasePoolPrint()
能够查看释放池的存储内容
extern void _objc_autoreleasePoolPrint(void);
int main(int argc, const char * argv[]) {
@autoreleasepool {//r1 = push()
FYPerson *p = [[FYPerson alloc]init];
_objc_autoreleasePoolPrint();
printf("\n--------------\n");
}//pop(r1)
return 0;
}
//log
objc[23958]: ##############
objc[23958]: AUTORELEASE POOLS for thread 0x1000aa5c0
objc[23958]: 3 releases pending.
objc[23958]: [0x101000000] ................ PAGE (hot) (cold)
objc[23958]: [0x101000038] ################ POOL 0x101000038
objc[23958]: [0x101000040] 0x10050cfa0 FYPerson
objc[23958]: [0x101000048] 0x10050cdb0 FYPerson
objc[23958]: ##############
--------------
复制代码
能够看到存储了3 releases pending
一个对象,并且大小都8字节。再看一个复杂的,自动释放池嵌套自动释放池
int main(int argc, const char * argv[]) {
@autoreleasepool {//r1 = push()
FYPerson *p = [[[FYPerson alloc]init] autorelease];
FYPerson *p2 = [[[FYPerson alloc]init] autorelease];
@autoreleasepool {//r1 = push()
FYPerson *p3 = [[[FYPerson alloc]init] autorelease];
FYPerson *p4 = [[[FYPerson alloc]init] autorelease];
_objc_autoreleasePoolPrint();
printf("\n--------------\n");
}//pop(r1)
}//pop(r1)
return 0;
}
//log
objc[24025]: ##############
objc[24025]: AUTORELEASE POOLS for thread 0x1000aa5c0
objc[24025]: 6 releases pending.
objc[24025]: [0x100803000] ................ PAGE (hot) (cold)
objc[24025]: [0x100803038] ################ POOL 0x100803038
objc[24025]: [0x100803040] 0x100721580 FYPerson
objc[24025]: [0x100803048] 0x100721b10 FYPerson
objc[24025]: [0x100803050] ################ POOL 0x100803050
objc[24025]: [0x100803058] 0x100721390 FYPerson
objc[24025]: [0x100803060] 0x100717620 FYPerson
objc[24025]: ##############
复制代码
看到了2个POOL
和四个FYPerson
对象,一共是6个对象,当出了释放池会执行release
。
当无优化的指针调用autorelease
实际上是调用了AutoreleasePoolPage::autorelease((id)this)
->autoreleaseFast(obj)
static inline id *autoreleaseFast(id obj)
{
AutoreleasePoolPage *page = hotPage();
//当有分页并且分页没有满就添加
if (page && !page->full()) {
return page->add(obj);
} else if (page) {
//满则新建一个page进行添加obj和设置hotpage
return autoreleaseFullPage(obj, page);
} else {
//没有page则新建page进行添加
return autoreleaseNoPage(obj);
}
}
复制代码
在MRC
中 autorealease
修饰的是的对象在没有外部添加到自动释放池的时候,在runloop
循环的时候会销毁
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0),
kCFRunLoopBeforeTimers = (1UL << 1),
kCFRunLoopBeforeSources = (1UL << 2),
kCFRunLoopBeforeWaiting = (1UL << 5),
kCFRunLoopAfterWaiting = (1UL << 6),
kCFRunLoopExit = (1UL << 7),
kCFRunLoopAllActivities = 0x0FFFFFFFU
};
//activities = 0xa0转化成二进制 0b101 0000
系统监听了mainRunloop 的 kCFRunLoopBeforeWaiting 和kCFRunLoopExit两种状态来更新autorelease的数据
//回调函数是 _wrapRunLoopWithAutoreleasePoolHandler
"<CFRunLoopObserver 0x600002538320 [0x10ce45ae8]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10f94087d), context = <CFArray 0x600001a373f0 [0x10ce45ae8]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7fb6dc004058>\n)}}"
复制代码
activities = 0xa0
转化成二进制 0b101 0000
系统监听了mainRunloop
的 kCFRunLoopBeforeWaiting
和kCFRunLoopExit
两种状态来更新autorelease
的数据 回调函数是 _wrapRunLoopWithAutoreleasePoolHandler
。
void test(){
FYPerson *p =[[FYPerson alloc]init];
}
复制代码
p
对象在某次循环中push
,在循环到kCFRunLoopBeforeWaiting
进行一次pop
,则上次循环的autolease
对象没有其余对象retain
的进行释放。并非出了test()
立马释放。
在ARC中则执行完毕test()
会立刻释放。
SideTable
中weak修饰的对象会在dealloc
函数执行过程当中检测或销毁该对象。objc_msgSend()
的消息流程从而提升性能。CADisplayLink
和Timer
本质是加到loop
循环当中,依附于循环,没有runloop
,则不能正确执行,使用runloop
须要注意循环引用和runloop
所在的线程的释放问题。最怕一辈子碌碌无为,还安慰本身平凡难得。
广告时间