-缓存概念
做过JavaWeb开发的人都知道,在Web应用程序中,整个系统的性能在于它的响应速度,因为Web系统往往采用Oracle,MySQL等大型数据库,如果系统响应速度过慢,那么就会降低用户体验,从而影响系统的性能和价值,所以有人提出缓存的概念
所谓缓存,就是用户执行一次查询操作后,查询的记录会放在缓存中。当用户再次查询时,系统会首先从缓存中读取,如果缓存中没有,再查询数据库。但是数据量过大时,缓存的作用就不大了。因为内存容量有限,所以又诞生了另一种技术,即懒加载
-懒加载
当用户滚动手机页面的时候自动获取更多的数据,而新得到的数据不会影响原有数据的显示,同时最大程度上减少服务器端的资源耗用
- 在ios中懒加载即延迟加载,即在只有用的时候才加载,此种加载效率低,占用内存小。因为懒加载写的是其get方法
- 如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化,比如以下代码中使用了if语句进行判断
本代码演示了采用懒加载方式从plist文件中加载数据
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#define IconKey @"icon"
#define DescKey @"desc"
#import "ViewController.h"
@interface ViewController ()
- (IBAction)previous;
- (IBAction)next;
//向前向后按钮
@property(weak,nonatomic)IBOutlet UIButton* previousBtn;
@property(weak,nonatomic)IBOutlet UIButton* nextBtn;
//两个文本标签和图像
@property (weak, nonatomic) IBOutlet UILabel *noLabel;
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UILabel *descriLabel;
//记录当前显示的是第几张图片
@property(nonatomic,assign)int index;
//图片数据集合
@property(nonatomic,strong)NSArray* imageData;
@end
使用懒加载的好处:
- 不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
- 每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//默认显示index为0对应的数据
[self changeData];
}
- (NSArray*) imageData
{
if (_imageData==nil) { //从未初始化
//数据初始化
NSBundle* bundle =[NSBundle mainBundle];
//获得imageData.plist的全路径
NSString* path =[bundle pathForResource:@"imageData" ofType:@"plist"];
_imageData =[NSArray arrayWithContentsOfFile:path];
}
return _imageData;
}
#pragma mark 改变数据
- (void)changeData
{
//1.改变数据
self.noLabel.text=[NSString stringWithFormat:@"%d/%lu",self.index+1,(unsigned long)self.imageData.count];
//2.取出index对应的数据字典
NSDictionary* imageDict =self.imageData[self.index];
//3.设置图片
self.icon.image=[UIImage imageNamed:imageDict[IconKey]];
//设置描述
self.descriLabel.text=imageDict[DescKey];
//5.改变按钮状态
self.previousBtn.enabled=(self.index!=0);
self.nextBtn.enabled=(self.index!=self.imageData.count-1);
}
@end
plist文件:
运行结果: