iOS-数据缓存

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRefresh = NO;
    if([[NSFileManager defaultManager] fileExistsAtPath:self.path])
    {
        [self loadDataFromFile];
    }
    else
    {
        [self loadDataFromServer];
    }
}


#pragma mark -- 从本地加载
- (void)loadDataFromFile
{
    NSData *fileData = [NSData dataWithContentsOfFile:self.path];
    NSDictionary *objects = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableContainers error:nil];
    if(!objects)
    {
        return;
    }
 
//    if(self.isRefresh == NO)
//    {
//        [self.data removeAllObjects];
//    }
     
    [self.data removeAllObjects];


    NSArray *dataArray = objects[@"data"];
    for(id node in dataArray)
    {
        // 不同的Model类
        self.obj = [self createDataWithJsonNode:node];
        [self.data addObject:self.obj];
    }
    self.isRefresh = NO;
    
}


#pragma mark -- 从网络加载
- (void)loadDataFromServer
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:self.url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if (responseObject) {
            // 把此文件路径下的内容全部删掉
            [[NSFileManager defaultManager] removeItemAtPath:self.path error:nil];
            
            // 存盘
            [operation.responseData writeToFile:self.path atomically:NO];
            [self loadDataFromFile];
            
            [self.tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"下载数据失败...");
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

你可能感兴趣的:(iOS-数据缓存)