iOS收录

iOS-浅谈内存管理

2018-09-01  本文已影响61人  梦蕊dream

前言:本文简述内存管理相关内容,如有错误请留言指正。

第一部分-定时器

1.1 NSTimer和CADisplayLink

NSTimer和CADisplayLink 是基于RunLoop的计时器

Q:NSTimer和target造成循环引用怎么解决?

//造成循环引用,控制器强引用timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

解决方法1:使用__weak搭配block来使用。

__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    [weakSelf timerTest];
}];

解决方案2:消息转发机制

@interface Proxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

#import "Proxy.h"

@implementation Proxy

+ (instancetype)proxyWithTarget:(id)target
{
    Proxy *proxy = [[Proxy alloc] init];
    proxy.target = target;
    return proxy;
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}

@end

// 保证调用频率和屏幕的刷帧频率一致,60FPS
self.link = [CADisplayLink displayLinkWithTarget:[Proxy proxyWithTarget:self] selector:@selector(linkTest)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

解决方案3:NSProxy
NSProxy和NSObject都是基类,NSProxy专门做消息转发的

@interface Proxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

#import "Proxy.h"

@implementation Proxy

+ (instancetype)proxyWithTarget:(id)target{
    // NSProxy对象不需要调用init,因为它本来就没有init方法
    Proxy *proxy = [Proxy alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation{
    [invocation invokeWithTarget:self.target];
}
@end

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

1.2 GCD定时器

NSTimer依赖于RunLoop,如果RunLoop的任务过于繁重,可能会导致NSTimer不准时。
GCD定时器和系统内核挂钩,不依赖RunLoop,GCD的定时器会更加准时。

GCD定时器使用:
封装GCD定时器demo代码:

#import <Foundation/Foundation.h>

@interface Timer : NSObject

+ (NSString *)execTask:(void(^)(void))task
           start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
         repeats:(BOOL)repeats
           async:(BOOL)async;

+ (NSString *)execTask:(id)target
              selector:(SEL)selector
                 start:(NSTimeInterval)start
              interval:(NSTimeInterval)interval
               repeats:(BOOL)repeats
                 async:(BOOL)async;

+ (void)cancelTask:(NSString *)name;

@end
#import "Timer.h"

@implementation Timer

static NSMutableDictionary *timers_;
dispatch_semaphore_t semaphore_;
+ (void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timers_ = [NSMutableDictionary dictionary];
        semaphore_ = dispatch_semaphore_create(1);
    });
}

+ (NSString *)execTask:(void (^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async
{
    if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
    
    // 队列
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
    
    // 创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间
    dispatch_source_set_timer(timer,
                              dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC),
                              interval * NSEC_PER_SEC, 0);
    
    
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    // 定时器的唯一标识
    NSString *name = [NSString stringWithFormat:@"%zd", timers_.count];
    // 存放到字典中
    timers_[name] = timer;
    dispatch_semaphore_signal(semaphore_);
    
    // 设置回调
    dispatch_source_set_event_handler(timer, ^{
        task();
        
        if (!repeats) { // 不重复的任务
            [self cancelTask:name];
        }
    });
    
    // 启动定时器
    dispatch_resume(timer);
    
    return name;
}

+ (NSString *)execTask:(id)target selector:(SEL)selector start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async
{
    if (!target || !selector) return nil;
    
    return [self execTask:^{
        if ([target respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [target performSelector:selector];
#pragma clang diagnostic pop
        }
    } start:start interval:interval repeats:repeats async:async];
}

+ (void)cancelTask:(NSString *)name
{
    if (name.length == 0) return;
    
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    
    dispatch_source_t timer = timers_[name];
    if (timer) {
        dispatch_source_cancel(timer);
        [timers_ removeObjectForKey:name];
    }

    dispatch_semaphore_signal(semaphore_);
}

@end

外部调用:

self.task = [Timer execTask:self
                         selector:@selector(doTask)
                            start:2.0
                         interval:1.0
                          repeats:YES
                            async:NO];
    
    self.task = [Timer execTask:^{
        NSLog(@"111111 - %@", [NSThread currentThread]);
    } start:2.0 interval:-10 repeats:NO async:NO];

1.3 内存布局

内存分为:代码段、数据段、堆区、栈区、内核区

内存布局图

第二部分-copy

iOS提供了2个拷贝方法:

深拷贝和浅拷贝

copy

不可变对象的拷贝:


image.png

可变对象的拷贝:


可变对象的拷贝

第三部分-内存管理

在iOS中,使用引用计数来管理OC对象的内存

内存管理的经验总结

可以通过以下私有函数来查看自动释放池的情况
extern void _objc_autoreleasePoolPrint(void);

2.1 引用计数存储

在64bit中,引用计数可以直接存储在优化过的isa指针中,也可能存储在SideTable类中
refcnts是一个存放着对象引用计数的散列表


sideTable

第四部分-weak/autorelease

4.1 weak指针实现原理

clearDeallocating()根据当前对象的地址值,根据哈希查找,找到对应的引用计数和弱引用,给清除掉
弱引用存在哈希表中,销毁时取出当前对象的弱引用表,把弱引用都清除掉。

当一个对象要释放时,会自动调用dealloc,接下的调用轨迹是

objc_destructInstance

Q:ARC帮我们做了什么?

LLVM编译器 + Runtime系统,相互协作的
ARC自动生成retain、release、autorelease

4.2 autorelease

自动释放池

源码分析
clang重写@autoreleasepool
objc4源码:NSObject.mm


源码截取

AutoreleasePoolPage的结构

Runloop和Autorelease

iOS在主线程的Runloop中注册了2个Observer
第1个Observer:

上一篇下一篇

猜你喜欢

热点阅读