美文网首页iOS 小册iOS点点滴滴
UIImage initWithData: 非线程安全

UIImage initWithData: 非线程安全

作者: fuyoufang | 来源:发表于2018-02-23 11:24 被阅读17次

在阅读 AFNetworking 的源码的时候,在 AFURLResponseSerialization.m 文件中看到如下代码:

@interface UIImage (AFNetworkingSafeImageLoading)
+ (UIImage *)af_safeImageWithData:(NSData *)data;
@end

static NSLock* imageLock = nil;

@implementation UIImage (AFNetworkingSafeImageLoading)

+ (UIImage *)af_safeImageWithData:(NSData *)data {
    UIImage* image = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imageLock = [[NSLock alloc] init];
    });
    
    [imageLock lock];
    image = [UIImage imageWithData:data];
    [imageLock unlock];
    return image;
}

@end

这段代码就是给 UIImage 添加了一个分类,可以通过 NSData 获取 UIImage,但是在转化过程中调用 imageWithData: 的前后加了锁。

原因是什么呢?

查了一下 AFN 的 issue,看到 Fix for issue #2572 Crash on AFImageWithDataAtScale when loading image

UIImage initWithData is not thread safe. In order to avoid crash we need to serialise call.

UIImage initWithData 并不是线程安全的。为了避免崩溃,需要按顺序调用,所以加了线程锁。

相关文章

  • UIImage initWithData: 非线程安全

    在阅读 AFNetworking 的源码的时候,在 AFURLResponseSerialization.m 文件...

  • UIKit-UIImage

    知识点一. UIImage的线程安全 文章提到UIImage的不可变性: UIImage一旦创建,就不能再改变它的...

  • String、StringBuffer、StringBuilde

    String 是字符串常量(线程安全);StringBuffer(线程安全), StringBuilder(非线程...

  • 2.1synchronized同步方法

    “线程安全”与“非线程安全”相关的技术点,它们是学习多线程技术时一定会遇到的经典问题。“非线程安全”其实会在多个线...

  • ConcurrentHashMap浅析

    简述 ConcurrentHashMap是针对HashMap非线程安全和HashTable低性能线程安全。它是线程...

  • ArrayList 和 LinkedList

    ArrayList非线程安全,基于数组对象,可数组扩容 LinkedList非线程安全 ,基于双向链表 ,无容量限...

  • 2.1.2实例变量非线程安全

    2.1.2实例变量非线程安全 如果多个线程共同访问1个对象中的实例变量,则有可能出现“非线程安全”问题。 程序运行...

  • 关于JAVA中各种Map的场景选择

    HashMap :非线程安全 存取速度快。 ConcurrentHashMap:并发场景使用 ,线程安全 Tree...

  • 线程安全与非线程安全

    线程安全 多线程访问时,对数据进行加锁保护,防止数据出现不一致或者数据污染情况。即:当一个线程要访问某类中的数据时...

  • 线程安全与非线程安全

    概念 一个线程中的实例变量针对其他线程有共享与不共享之分,这个在多线程之间交互时是很重要的一个技术点。数据不共享的...

网友评论

    本文标题:UIImage initWithData: 非线程安全

    本文链接:https://www.haomeiwen.com/subject/jtztxftx.html