如果看过 保持界面流畅技巧
这篇文章肯定会对AsyncDisplayKit 有强烈的好奇心。
此文章系 AsyncDisplayKit 的源码阅读笔记。零散的记录一些点。读完了说不定就能开始分析 AsyncDisplayKit 了
1:后台释放变量
void ASPerformBlockOnDeallocationQueue(void (^block)())
{
static dispatch_queue_t queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
queue = dispatch_queue_create("org.AsyncDisplayKit.deallocationQueue", DISPATCH_QUEUE_SERIAL);
});
dispatch_async(queue, block);
}
ASPerformBlockOnDeallocationQueue
用来释放对象在后台线程,让界面更流畅。 比如应用
- (void)_clearImage
{
// Destruction of bigger images on the main thread can be expensive
// and can take some time, so we dispatch onto a bg queue to
// actually dealloc.
__block UIImage *image = self.image;
CGSize imageSize = image.size;
BOOL shouldReleaseImageOnBackgroundThread = imageSize.width > kMinReleaseImageOnBackgroundSize.width ||
imageSize.height > kMinReleaseImageOnBackgroundSize.height;
if (shouldReleaseImageOnBackgroundThread) {
ASPerformBlockOnDeallocationQueue(^{
image = nil;
});
}
///TODO
///
根据注释看,说大图在主线程释放的时候会消耗更好的性能和时间。此处,最小尺寸是
static const CGSize kMinReleaseImageOnBackgroundSize = {20.0, 20.0};
20x20尺寸的图,在我们的应用里比这个大很多的多的是吧!但是从来没有想过,要在其他线程释放!
所以 AsyncDisplayKit 性能好是有道理的,性能处理,做到极致!!
2:一些特定的方法只能在父类中实现。
BOOL ASSubclassOverridesSelector(Class superclass, Class subclass, SEL selector)
{
Method superclassMethod = class_getInstanceMethod(superclass, selector);
Method subclassMethod = class_getInstanceMethod(subclass, selector);
IMP superclassIMP = superclassMethod ? method_getImplementation(superclassMethod) : NULL;
IMP subclassIMP = subclassMethod ? method_getImplementation(subclassMethod) : NULL;
return (superclassIMP != subclassIMP);
}
ASSubclassOverridesSelector
用来判断子类是不是实现了父类的某个方法,用法,配合#define ASDisplayNodeAssert(...) NSAssert(__VA_ARGS__)
宏,在initialize
方法中进行断言,某些方法,子类一定不能实现。。
比如ASImageNode
中
+ (void)initialize
{
[super initialize];
if (self != [ASImageNode class]) {
// Prevent custom drawing in subclasses
ASDisplayNodeAssert(!ASSubclassOverridesClassSelector([ASImageNode class], self, @selector(displayWithParameters:isCancelled:)), @"Subclass %@ must not override displayWithParameters:isCancelled: method. Custom drawing in %@ subclass is not supported.", NSStringFromClass(self), NSStringFromClass([ASImageNode class]));
}
}
3:任务放到主线程的正确姿势
void ASPerformBlockOnMainThread(void (^block)())
{
if (block == nil){
return;
}
if (ASDisplayNodeThreadIsMain()) {
block();
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
如果不做判断,就会让任务执行的时机发生变化!
4:消耗性能的操作,尽量只做一次求值操作
比如:
CGFloat ASScreenScale()
{
static CGFloat __scale = 0.0;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ASDisplayNodeCAssertMainThread();
__scale = [[UIScreen mainScreen] scale];
});
return __scale;
}
ASScreenScale
的调用时机在 ASDisplayNode
的 load
方法中
+ (void)load
{
// Ensure this value is cached on the main thread before needed in the background.
ASScreenScale();
}
确保scale 的值已经计算好了,并且是在主线程中计算的。因为使用UIKit相关代码了,所以一定要确保在主线程。
5:ASSentinel
ASSentinel
的作用是防止 layer 被重复渲染使用的,比如,一个layer 已经超出屏幕或者下一次渲染的数据已经来了,那么,需要一个标示,来标记,此次不用渲染了。
@interface ASSentinel : NSObject
- (int32_t)value;
- (int32_t)increment;
@end
定义很简单,返回一个值,increment 递增当前的值。
在基类的 _initializeInstance
函数中初始化,
_displaySentinel = [[ASSentinel alloc] init];
在需要关闭当前渲染的时候进行自增
- (void)cancelDisplayAsyncLayer:(_ASDisplayLayer *)asyncLayer
{
[_displaySentinel increment];
}
或者
- (void)cancelAsyncDisplay
{
ASDisplayNodeAssertMainThread();
[_displaySentinel increment];
.........
}
delegate 函数的判断,也可以使用结构体标示有没有实现某个方法,比如:
struct ASDisplayNodeFlags {
// public properties
unsigned synchronous:1;
unsigned layerBacked:1;
unsigned displaysAsynchronously:1;
unsigned shouldRasterizeDescendants:1;
unsigned shouldBypassEnsureDisplay:1;
unsigned displaySuspended:1;
unsigned shouldAnimateSizeChanges:1;
unsigned hasCustomDrawingPriority:1;
}
具体使用如下(ps鄙人项目中的使用):
struct {
unsigned hasJingxiangAction:1;
unsigned hasCameraAction :1;
unsigned hasMuteAction :1;
unsigned hasRoomManagerAction:1;
unsigned hasFollowlistAction:1;
}_delefateAction; ///<delelgate 行为
设置代理的时候
- (void)setDelegate:(id<PXYMoreActionDelegate>)delegate {
_delegate = delegate;
_delefateAction.hasJingxiangAction = [_delegate respondsToSelector:@selector(jingxiangAction)];
_delefateAction.hasCameraAction = [_delegate respondsToSelector:@selector(cameraAction)];
_delefateAction.hasMuteAction = [_delegate respondsToSelector:@selector(muteAction)];
_delefateAction.hasRoomManagerAction = [_delegate respondsToSelector:@selector(roomManagerAciton)];
_delefateAction.hasFollowlistAction = [_delegate respondsToSelector:@selector(followerListAction)];
}
不用每次都调用respondsToSelector
方法,稍微提升一点效率,使用的时候就可以这样子判断了
if (_delefateAction.hasRoomManagerAction) {
[_delegate roomManagerAciton];
}
省去了之前繁琐的判断。
华丽分割线!!!!
我们看看 node 是什么时候创建 view 或者 layer 的。(显示视图,肯定是 view或者layer了)
- (void)addSubnode:(ASDisplayNode *)subnode
{
///断言 #省略
ASDisplayNodeAssert(subnode, @"Cannot insert a nil subnode");
ASDisplayNode *oldParent = subnode.supernode;
///#不能重复添加或者自己添加自己
if (!subnode || subnode == self || oldParent == self) {
return;
}
///#添加子节点
BOOL isMovingEquivalentParents = disableNotificationsForMovingBetweenParents(oldParent, self);
if (isMovingEquivalentParents) {
[subnode __incrementVisibilityNotificationsDisabled];
}
[subnode removeFromSupernode];
if (!_subnodes) {
_subnodes = [[NSMutableArray alloc] init];
}
[_subnodes addObject:subnode];
// This call will apply our .hierarchyState to the new subnode.
// If we are a managed hierarchy, as in ASCellNode trees, it will also apply our .interfaceState.
[subnode __setSupernode:self];
///#如果当前的node 已经有 view 或者 layer 就给子节点同样创建一个 view 或者 layer并且添加进来。。
if (self.nodeLoaded) {
ASPerformBlockOnMainThread(^{
[self _addSubnodeSubviewOrSublayer:subnode];
});
}
ASDisplayNodeAssert(isMovingEquivalentParents == disableNotificationsForMovingBetweenParents(oldParent, self), @"Invariant violated");
if (isMovingEquivalentParents) {
[subnode __decrementVisibilityNotificationsDisabled];
}
}
从流程上看,在 addSubnode 的时候,如果父node已经有显示出来了,就创建。
还有另外一种情况,调用 view的 addSubnode 方法:
- (void)addSubnode:(ASDisplayNode *)subnode
{
if (subnode.layerBacked) {
// Call -addSubnode: so that we use the asyncdisplaykit_node path if possible.
[self.layer addSubnode:subnode];
} else {
ASDisplayNode *selfNode = self.asyncdisplaykit_node;
if (selfNode) {
[selfNode addSubnode:subnode];
} else {
[self addSubview:subnode.view];
}
}
}
最后如果一步 [self addSubview:subnode.view];的时候,就开始走 view的创建流程了。
view 的创建流程:
- (UIView *)view
{
if (_flags.layerBacked) {
return nil;
}
if (!_view) {
ASDisplayNodeAssertMainThread();
[self _loadViewOrLayerIsLayerBacked:NO];
}
return _view;
}
- (CALayer *)layer
{
if (!_layer) {
ASDisplayNodeAssertMainThread();
if (!_flags.layerBacked) {
return self.view.layer;
}
[self _loadViewOrLayerIsLayerBacked:YES];
}
return _layer;
}
创建 view 或者 layer 的时候,都会使用 ASDisplayNodeAssertMainThread(); 宏来限定,只能在主线程创建。。最后都会调用
_loadViewOrLayerIsLayerBacked
函数。如果创建layer 传入 YES 创建 view 传入 NO
- (void)_loadViewOrLayerIsLayerBacked:(BOOL)isLayerBacked
{
/// 如果node 已经是释放状态,不创建
if (self._isDeallocating) {
return;
}
/// 如果没有父节点,直接返回
if (![self __shouldLoadViewOrLayer]) {
return;
}
/// 创建 layer
if (isLayerBacked) {
_layer = [self _layerToLoad];
_layer.delegate = (id<CALayerDelegate>)self;
} else {
/// 创建 view
_view = [self _viewToLoad];
_view.asyncdisplaykit_node = self;
_layer = _view.layer;
}
_layer.asyncdisplaykit_node = self;
self.asyncLayer.asyncDelegate = self;
///# 其他状态设置
......
}
创建view 的过程 如下:
- (UIView *)_viewToLoad
{
UIView *view;
ASDN::MutexLocker l(__instanceLock__);
if (_viewBlock) {
view = _viewBlock();
ASDisplayNodeAssertNotNil(view, @"View block returned nil");
ASDisplayNodeAssert(![view isKindOfClass:[_ASDisplayView class]], @"View block should return a synchronously displayed view");
_viewBlock = nil;
_viewClass = [view class];
} else {
if (!_viewClass) {
_viewClass = [self.class viewClass];
}
view = [[_viewClass alloc] init];
}
// Update flags related to special handling of UIImageView layers. More details on the flags
if (_flags.synchronous && [_viewClass isSubclassOfClass:[UIImageView class]]) {
_flags.canClearContentsOfLayer = NO;
_flags.canCallSetNeedsDisplayOfLayer = NO;
}
return view;
}
如果初始化的时候有提供_viewBlock,就是用 _viewBlock 返回一个view,要么就是用默认的view进行创建。
+ (Class)viewClass
{
return [_ASDisplayView class];
}
+ (Class)layerClass
{
return [_ASDisplayLayer class];
}
ASDisplayNode
提供了内置的 view 和 layer ,_ASDisplayView 用来转发一些事件,_ASDisplayLayer 是 性能提升的关键。
从上面可以看出 node 节点就是包装了 view 和 layer 的 载体,可以通过node 设置 view 或者 layer的属性。在view 或者 layer需要显示的时候,把属性设置上去。
这里忽略掉了布局相关的代码。以后有空了补补
_ASDisplayView
_ASDisplayView 是 ASDisplayNode 的 一个私有类,只能在ASDisplayNode 中使用,不能继承和重写。前面有提到过
+ (Class)viewClass
{
return [_ASDisplayView class];
}
_ASDisplayView 的 作用就是重写了UIView的一些方法用来转发一些事件给 ASDisplayNode,下面,我们看看主要的函数。
+ (Class)layerClass
{
return [_ASDisplayLayer class];
}
重写 layerClass 函数,使用可以异步绘制的 类 _ASDisplayLayer。
- (void)willMoveToWindow:(UIWindow *)newWindow
{
BOOL visible = (newWindow != nil);
if (visible && !_node.inHierarchy) {
[_node __enterHierarchy];
}
}
将要添加到window上的时候,把事件转给Node. 当然还有其他的类似 didMoveToWindow
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_node.methodOverrides & ASDisplayNodeMethodOverrideTouchesBegan) {
[_node touchesBegan:touches withEvent:event];
} else {
[super touchesBegan:touches withEvent:event];
}
}
touche 系列的函数的重写,判断当前node 是否实现了对应的方法,如果实现了,就把事件转发给node. ASControlNode
的实现,就得益于touch 函数的转发。
分割线
判断两个obj是否相等
ASDISPLAYNODE_INLINE BOOL ASObjectIsEqual(id<NSObject> obj, id<NSObject> otherObj)
{
return obj == otherObj || [obj isEqual:otherObj];
}
参数可以为nil 此处!
_ASDisplayLayer
看看_ASDisplayLayer 的实现。
typedef BOOL(^asdisplaynode_iscancelled_block_t)(void);
用来标示当前异步的操作是否已经结束
@interface _ASDisplayLayer : CALayer
///#设置是否异步展示
@property (nonatomic, assign) BOOL displaysAsynchronously;
///#关闭当前的异步展示
- (void)cancelAsyncDisplay;
///#异步展示的队列
+ (dispatch_queue_t)displayQueue;
///#计数器,之前讲过的
@property (nonatomic, strong, readonly) ASSentinel *displaySentinel;
///#展示过程中的代理
@property (nonatomic, weak) id<_ASDisplayLayerDelegate> asyncDelegate;
///#挂起异步显示
@property (nonatomic, assign, getter=isDisplaySuspended) BOOL displaySuspended;
///#直接展示
- (void)displayImmediately;
ASCALayerExtendedDelegate
bounds 改变的时候回调用这个代理的方法。
_ASDisplayLayerDelegate
异步渲染的时候一些回调,node 可以实现这些方法,来实现自己的渲染,
_ASDisplayLayer实现
- (instancetype)init
{
if ((self = [super init])) {
_displaySentinel = [[ASSentinel alloc] init];
self.opaque = YES;
}
return self;
}
_displaySentinel 初始化异步展示关闭的条件。
看一些主要的方法。
+ (id)defaultValueForKey:(NSString *)key
{
if ([key isEqualToString:@"displaysAsynchronously"]) {
return @YES;
} else {
return [super defaultValueForKey:key];
}
}
设置layer的默认的属性值,这是设置 displaysAsynchronously 默认为 YES。(默认开启异步展示效果)
- (void)setNeedsDisplay
{
///#判断是不是主线程
ASDisplayNodeAssertMainThread();
///#线程锁
_displaySuspendedLock.lock();
///关闭当前的绘制,已经在绘制的不能被关闭,如果还没有开始绘制,但是在队列里面,是能关闭的
[self cancelAsyncDisplay];
// Short circuit if display is suspended. When resumed, we will setNeedsDisplay at that time.
if (!_displaySuspended) {
[super setNeedsDisplay];
}
_displaySuspendedLock.unlock();
}
setNeedsDisplay 设置内容需要重新绘制。开始绘制之前,先关闭上次还没有开始绘制的任务!
+ (dispatch_queue_t)displayQueue
{
static dispatch_queue_t displayQueue = NULL;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
displayQueue = dispatch_queue_create("org.AsyncDisplayKit.ASDisplayLayer.displayQueue", DISPATCH_QUEUE_CONCURRENT);
// we use the highpri queue to prioritize UI rendering over other async operations
dispatch_set_target_queue(displayQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
});
return displayQueue;
}
displayQueue 异步绘制的队列。注意,队列是 DISPATCH_QUEUE_CONCURRENT 并行的。并且 dispatch_set_target_queue 设置的 DISPATCH_QUEUE_PRIORITY_HIGH。跟UI绘制相关的队列,优先级最高。
- (void)display
{
///#此方法只能在主线程调用
ASDisplayNodeAssertMainThread();
[self _hackResetNeedsDisplay];
///如果已经挂起了,返回
if (self.isDisplaySuspended) {
return;
}
///开始调用绘制
[self display:self.displaysAsynchronously];
}
- (void)display:(BOOL)asynchronously
{
///如果大小为0 的时候是否绘制
if (CGRectIsEmpty(self.bounds)) {
_attemptedDisplayWhileZeroSized = YES;
}
id<_ASDisplayLayerDelegate> NS_VALID_UNTIL_END_OF_SCOPE strongAsyncDelegate;
{
_asyncDelegateLock.lock();
strongAsyncDelegate = _asyncDelegate;
_asyncDelegateLock.unlock();
}
///开始调用代理的方法,进行绘制
[strongAsyncDelegate displayAsyncLayer:self asynchronously:asynchronously];
}
so,绘制部分交给了代理,也就是Node....ok,我们看一下node的绘制部分。。。
相关代码在ASDisplayNode+AsyncDisplay.mm
文件中
- (void)displayAsyncLayer:(_ASDisplayLayer *)asyncLayer asynchronously:(BOOL)asynchronously
{
///必须在主线程进行
ASDisplayNodeAssertMainThread();
///上锁
ASDN::MutexLocker l(__instanceLock__);
if (_hierarchyState & ASHierarchyStateRasterized) {
return;
}
///判断有没有取消当前绘制的block
ASSentinel *displaySentinel = (asynchronously ? _displaySentinel : nil);
int32_t displaySentinelValue = [displaySentinel increment];
asdisplaynode_iscancelled_block_t isCancelledBlock = ^{
return BOOL(displaySentinelValue != displaySentinel.value);
};
///生成绘制的block 返回一个image 直接设置在layer上
asyncdisplaykit_async_transaction_operation_block_t displayBlock = [self _displayBlockWithAsynchronous:asynchronously isCancelledBlock:isCancelledBlock rasterizing:NO];
///#如果没有绘制的block,那就没有必要进行了
if (!displayBlock) {
return;
}
///插入runloop的block
ASDisplayNodeAssert(_layer, @"Expect _layer to be not nil");
asyncdisplaykit_async_transaction_operation_completion_block_t completionBlock = ^(id<NSObject> value, BOOL canceled){
ASDisplayNodeCAssertMainThread();
if (!canceled && !isCancelledBlock()) {
UIImage *image = (UIImage *)value;
BOOL stretchable = (NO == UIEdgeInsetsEqualToEdgeInsets(image.capInsets, UIEdgeInsetsZero));
if (stretchable) {
ASDisplayNodeSetupLayerContentsWithResizableImage(_layer, image);
} else {
_layer.contentsScale = self.contentsScale;
_layer.contents = (id)image.CGImage;
}
[self didDisplayAsyncLayer:self.asyncLayer];
}
};
///调用即将渲染layer的函数
[self willDisplayAsyncLayer:self.asyncLayer];
if (asynchronously) {///如果是异步的,加入到runloop中
// Async rendering operations are contained by a transaction, which allows them to proceed and concurrently
// while synchronizing the final application of the results to the layer's contents property (completionBlock).
// First, look to see if we are expected to join a parent's transaction container.
CALayer *containerLayer = _layer.asyncdisplaykit_parentTransactionContainer ? : _layer;
// In the case that a transaction does not yet exist (such as for an individual node outside of a container),
// this call will allocate the transaction and add it to _ASAsyncTransactionGroup.
// It will automatically commit the transaction at the end of the runloop.
_ASAsyncTransaction *transaction = containerLayer.asyncdisplaykit_asyncTransaction;
// Adding this displayBlock operation to the transaction will start it IMMEDIATELY.
// The only function of the transaction commit is to gate the calling of the completionBlock.
[transaction addOperationWithBlock:displayBlock priority:self.drawingPriority queue:[_ASDisplayLayer displayQueue] completion:completionBlock];
} else {
///不是异步,直接把image,设置在layer上!!
UIImage *contents = (UIImage *)displayBlock();
completionBlock(contents, NO);
}
}
此处,相关技术可以通过YY大神博客了解 保持界面流畅技巧
网友评论