您的位置:首页 > 移动开发 > IOS开发

iOS 开发缓存机制之一内存缓存机制

2016-12-02 19:34 411 查看
iOS应用程序开发中,为了减少与服务端的交互次数,加快用户的响应速度,一般都会在iOS设备中加一个缓存的机制。

这篇文章将介绍一下如何在iOS设备中进行缓存,本文先介绍一下将内容缓存到内存中,下一篇文章就介绍一下在iOS磁盘上缓存内容。

使用缓存的目的是为了使用的应用程序能更快速的响应用户输入,是程序高效的运行。有时候我们需要将远程web服务器获取的数据缓存起来,减少对同一个url多次请求。

内存缓存我们可以使用sdk中的NSURLCache类。NSURLRequest需要一个缓存参数来说明它请求的url何如缓存数据的,我们先看下它的CachePolicy类型。

1、NSURLRequestUseProtocolCachePolicy NSURLRequest默认的cache policy,使用Protocol协议定义。

2、NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载。

3、NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载。

4、NSURLRequestReturnCacheDataDontLoad 只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式;

5、NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。

6、NSURLRequestReloadRevalidatingCacheData:验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据。

NSURLCache还提供了很多方法,来方便我们实现应用程序的缓存机制。下面我通过一个例子来说明,这个例子减少我们对同一个url多次请求。看下面代码:

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];

    button.frame =CGRectMake(100,100,
100,50);

    [button setTitle:@"按钮"forState:UIControlStateNormal];

    [button addTarget:selfaction:@selector(buttonPress:)forControlEvents:UIControlEventTouchUpInside];

    

    NSString *paramURLAsString =@"http://stackoverflow.com/questions/30778579/kcfstreamerrordomainssl-9802-when-connecting-to-a-server-by-ip-address-through";

    objc_setAssociatedObject(button, &buttonAttri, paramURLAsString,OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    

    [self.viewaddSubview:button];

}

- (void)buttonPress:(id)sender {

    NSString *paramURLAsString =objc_getAssociatedObject(sender, &buttonAttri);

    NSLog(@"paramURLAsString: %@", paramURLAsString);

    

    if (paramURLAsString.length ==0) {

        NSLog(@"Nil or empty URL is given");

        return;

    }

    

    //单例类

    NSURLCache *urlCache = [NSURLCachesharedURLCache];

    //set chache size to 1M

    [urlCache setMemoryCapacity:1 *1024 *
1024];

    

    //创建一个nsurl

    NSURL *url = [NSURLURLWithString:paramURLAsString];

    //创建一个请求

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url

                                                          
cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:10.0f];

   //从缓存中获取缓存输出

    NSCachedURLResponse *response = [urlCachecachedResponseForRequest:request];

    

   //判断是否有缓存

    if (response !=nil) {

        NSLog(@"如果有缓存输出,从缓存中获取数据");

        [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];

    }

    

    self.connection =nil;

    //创建NSURLConnection

    NSURLConnection *newConnection = [[NSURLConnectionalloc]
initWithRequest:requestdelegate:selfstartImmediately:YES];

    self.connection = newConnection;

}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response

{

    NSLog(@"准备接受输出!");

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData
*)data

{

    NSLog(@"接收数据!");

    NSLog(@"数据长度:
%ld", data.length);

}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest
*)request

            redirectResponse:(NSURLResponse *)response

{

    NSLog(@"将发送请求");

    return request;

}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection

                  willCacheResponse:(NSCachedURLResponse *)cachedResponse

{

    NSLog(@"将缓存输出");

    return cachedResponse;

}

输出结果:

2016-12-02 18:18:07.680 NSURLCache内存缓存机制[1551:908970] paramURLAsString: http://stackoverflow.com/questions/30778579/kcfstreamerrordomainssl-9802-when-connecting-to-a-server-by-ip-address-through
2016-12-02 18:18:07.703 NSURLCache内存缓存机制[1551:908970]将发送请求

2016-12-02 18:18:08.420 NSURLCache内存缓存机制[1551:908970]准备接受输出!

2016-12-02 18:18:08.420 NSURLCache内存缓存机制[1551:908970]接收数据!

2016-12-02 18:18:08.420 NSURLCache内存缓存机制[1551:908970]数据长度:
14125


2016-12-02 18:18:08.767 NSURLCache内存缓存机制[1551:908970]接收数据!

2016-12-02 18:18:08.768 NSURLCache内存缓存机制[1551:908970]数据长度:
85000


2016-12-02 18:18:09.546 NSURLCache内存缓存机制[1551:908970]接收数据!

2016-12-02 18:18:09.547 NSURLCache内存缓存机制[1551:908970]数据长度:
2306


2016-12-02 18:18:09.547 NSURLCache内存缓存机制[1551:908970]将缓存输出

2016-12-02 19:31:28.098 NSURLCache内存缓存机制[1551:908970] paramURLAsString: http://stackoverflow.com/questions/30778579/kcfstreamerrordomainssl-9802-when-connecting-to-a-server-by-ip-address-through
2016-12-02 19:31:28.105 NSURLCache内存缓存机制[1551:908970]如果有缓存输出,从缓存中获取数据

2016-12-02 19:31:28.106 NSURLCache内存缓存机制[1551:908970]将发送请求

2016-12-02 19:31:28.107 NSURLCache内存缓存机制[1551:908970]准备接受输出!

2016-12-02 19:31:28.107 NSURLCache内存缓存机制[1551:908970]接收数据!

2016-12-02 19:31:28.107 NSURLCache内存缓存机制[1551:908970]数据长度:
101431
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: