多线程知识点(五)

  1. 使用SD下载图片

#import "UIImageView+WebCache.h"

[self.HMImageView sd_setImageWithURL:url placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {

//receivedSize 接收到的文件大小, expectedSize文件的总大小} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {    }];

 

  1. 使用SD下载GIF

#import "UIImage+GIF.h"

//方式1:

self.HMImageView.image = [UIImage sd_animatedGIFNamed:@"2"];

//方式2

  //获取图片路径

    NSString *path = [[NSBundle mainBundle]pathForResource:@"2.gif" ofType:nil];

    //转成二进制

    NSData *data = [NSData dataWithContentsOfFile:path];

   

    self.HMImageView.image = [UIImage sd_animatedGIFWithData:data];

  1. 使用系统自带的cache,使用方式与字典相同

第一步:

//全局cache

@property(nonatomic,strong)NSCache *cache;

第二步:

- (NSCache *)cache{

    if (_cache == nil) {

        _cache = [[NSCache alloc]init];

                //设置缓存数量

        _cache.countLimit = 5

    }

    return _cache;

}

 第三步:

存取数据

//存储数据

        [self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"haha %d",i]];

第四步:

读取数据

NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"haha %d",i]]);

缓存移除的时候调用的方法

第一步遵守协议<NSCacheDelegate>

//对象将要被移除的时候调用

- (void)cache:(NSCache *)cache willEvictObject:(id)obj

{

    NSLog(@"willEvict %@",obj);

}

4:消息循环: runloop

    每一个线程内部都有一个消息循环

只有主线程的消息循环默认开启,子线程的消息循环默认不开启

5:消息循环的作用:

1:能够保证应用程序不退出

2: 能够处理输入事件

6. 输入事件的模式必须和消息循环的模式相互匹配,才能够执行输入事件的代码NSDefaultRunLoopMode ,NSRunLoopCommonModes(包括其余两个) UITrackingRunLoopMode

7.设置消息循环的模式:

[[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];

8.开启子线程:[[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];

9.开启子线程

[self performSelector:@selector(demo) onThread:thread withObject:nil waitUntilDone:NO];

10.子线程的消息循环(死循环)默认是不开启的,手动开启

[[NSRunLoop currentRunLoop]run];

或者,定时

[[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];

原文地址:https://www.cnblogs.com/chaoyueME/p/5575188.html