IOS之分析网易新闻存储数据(CoreData的使用,增删改查)
用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的。
首先:
1、网易新闻用CoreData存储了新闻列表,因为我打开网易新闻的Documents时看到了三个文件:
newsapp.sqlite,newsapp.sqlite-shm,newsapp.sqlite-wal:这三个文件是你在用CoreData时自动生成的。所以我确定他是用coredata存储的数据而不是sqlite数据库。(CoreData优点:能够合理管理内存,避免使用sql的麻烦,高效)
2、网易会隔一断时间请求一次网络,具体时间有可能是隔8个小时或者5个小时或者3个小时都有可能,这个我无法确定时间。反正确实在一定时间后会清空一下数据库并且添加新的请求来的新闻。
3、查看网易新闻后会有一个记录状态,表示已看过,这个也在数据库中存储着。
我这里就简单的实现一下网易新闻的界面,主要讲一下如何用CoreData存储数据,并实现增删改查。
实现的效果:
Demo下载地址:http://download.csdn.net/detail/rhljiayou/6833273
如果Demo打不开请选择一下版本:
首先关于UItableViewCell的使用,大家可以参考此博文:IOS高访新浪微博界面(讲解如何自定义UITableViewCell,处理@#链接 特殊字符)
接下来是如何创建CoreData:
命名为NewsModel:
添加CoreData框架
导入#import<CoreData/CoreData.h>
贴代码之前需要了解6个对象:
1、NSManagedObjectContext
管理对象,上下文,持久性存储模型对象
2、NSManagedObjectModel
被管理的数据模型,数据结构
3、NSPersistentStoreCoordinator
连接数据库的
4、NSManagedObject
被管理的数据记录
5、NSFetchRequest
数据请求
6、NSEntityDescription
表格实体结构
此外还需要知道.xcdatamodel文件编译后为.momd或者.mom文件
以下是封装好的CoreData管理类CoreDataManager.h:
- #import <Foundation/Foundation.h>
- #import "News.h"
- #define TableName @"News"
- @interface CoreDateManager : NSObject
- @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
- @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
- @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- - (void)saveContext;
- - (NSURL *)applicationDocumentsDirectory;
- //插入数据
- - (void)insertCoreData:(NSMutableArray*)dataArray;
- //查询
- - (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage;
- //删除
- - (void)deleteData;
- //更新
- - (void)updateData:(NSString*)newsId withIsLook:(NSString*)islook;
- @end
以下是.m的实现:
- //
- // CoreDateManager.m
- // SQLiteTest
- //
- // Created by rhljiayou on 14-1-8.
- // Copyright (c) 2014年 rhljiayou. All rights reserved.
- //
- #import "CoreDateManager.h"
- @implementation CoreDateManager
- @synthesize managedObjectContext = _managedObjectContext;
- @synthesize managedObjectModel = _managedObjectModel;
- @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- - (void)saveContext
- {
- NSError *error = nil;
- NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
- if (managedObjectContext != nil) {
- if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- }
- }
- #pragma mark - Core Data stack
- // Returns the managed object context for the application.
- // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- - (NSManagedObjectContext *)managedObjectContext
- {
- if (_managedObjectContext != nil) {
- return _managedObjectContext;
- }
- NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
- if (coordinator != nil) {
- _managedObjectContext = [[NSManagedObjectContext alloc] init];
- [_managedObjectContext setPersistentStoreCoordinator:coordinator];
- }
- return _managedObjectContext;
- }
- // Returns the managed object model for the application.
- // If the model doesn't already exist, it is created from the application's model.
- - (NSManagedObjectModel *)managedObjectModel
- {
- if (_managedObjectModel != nil) {
- return _managedObjectModel;
- }
- NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"NewsModel" withExtension:@"momd"];
- _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
- return _managedObjectModel;
- }
- // Returns the persistent store coordinator for the application.
- // If the coordinator doesn't already exist, it is created and the application's store added to it.
- - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
- {
- if (_persistentStoreCoordinator != nil) {
- return _persistentStoreCoordinator;
- }
- NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"NewsModel.sqlite"];
- NSError *error = nil;
- _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
- if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return _persistentStoreCoordinator;
- }
- #pragma mark - Application's Documents directory
- // Returns the URL to the application's Documents directory.获取Documents路径
- - (NSURL *)applicationDocumentsDirectory
- {
- return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
- }
- //插入数据
- - (void)insertCoreData:(NSMutableArray*)dataArray
- {
- NSManagedObjectContext *context = [self managedObjectContext];
- for (News *info in dataArray) {
- News *newsInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];
- newsInfo.newsid = info.newsid;
- newsInfo.title = info.title;
- newsInfo.imgurl = info.imgurl;
- newsInfo.descr = info.descr;
- newsInfo.islook = info.islook;
- NSError *error;
- if(![context save:&error])
- {
- NSLog(@"不能保存:%@",[error localizedDescription]);
- }
- }
- }
- //查询
- - (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage
- {
- NSManagedObjectContext *context = [self managedObjectContext];
- // 限定查询结果的数量
- //setFetchLimit
- // 查询的偏移量
- //setFetchOffset
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
- [fetchRequest setFetchLimit:pageSize];
- [fetchRequest setFetchOffset:currentPage];
- NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];
- [fetchRequest setEntity:entity];
- NSError *error;
- NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
- NSMutableArray *resultArray = [NSMutableArray array];
- for (News *info in fetchedObjects) {
- NSLog(@"id:%@", info.newsid);
- NSLog(@"title:%@", info.title);
- [resultArray addObject:info];
- }
- return resultArray;
- }
- //删除
- -(void)deleteData
- {
- NSManagedObjectContext *context = [self managedObjectContext];
- NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];
- NSFetchRequest *request = [[NSFetchRequest alloc] init];
- [request setIncludesPropertyValues:NO];
- [request setEntity:entity];
- NSError *error = nil;
- NSArray *datas = [context executeFetchRequest:request error:&error];
- if (!error && datas && [datas count])
- {
- for (NSManagedObject *obj in datas)
- {
- [context deleteObject:obj];
- }
- if (![context save:&error])
- {
- NSLog(@"error:%@",error);
- }
- }
- }
- //更新
- - (void)updateData:(NSString*)newsId withIsLook:(NSString*)islook
- {
- NSManagedObjectContext *context = [self managedObjectContext];
- NSPredicate *predicate = [NSPredicate
- predicateWithFormat:@"newsid like[cd] %@",newsId];
- //首先你需要建立一个request
- NSFetchRequest * request = [[NSFetchRequest alloc] init];
- [request setEntity:[NSEntityDescription entityForName:TableName inManagedObjectContext:context]];
- [request setPredicate:predicate];//这里相当于sqlite中的查询条件,具体格式参考苹果文档
- //https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
- NSError *error = nil;
- NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组,你需要取出你要更新的那个obj
- for (News *info in result) {
- info.islook = islook;
- }
- //保存
- if ([context save:&error]) {
- //更新成功
- NSLog(@"更新成功");
- }
- }
- @end
此句:
- NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"NewsModel.sqlite"];
生成以后,你可以在Documents下面看到三个文件:
那么你可以打开NewsModel.sqlite文件看一下里面的表格:
Z_METADATA里面记录了一个本机的UUID。
Z_PRIMARYKEY里面是所有自己创建的表格的名字。
ZNEWS是自己创建的表格,打开里面就是我们的数据记录。
此外你需要了解查询时候需要正则表达式:(官方的)
使用是只要:coreManager = [[CoreDateManageralloc]init];创建对象
增删改查:
- //增
- [coreManager insertCoreData:_resultArray];
- //删
- [coreManager deleteData];
- //改
- [coreManager updateData:info.newsid withIsLook:@"1"];
- //查
- [coreManager selectData:10 andOffset:0];</span>
具体实现看源码。
CoreData很强大,用起来很方便,是一个不错的存储数据的好方法。
ok!
IOS之分析网易新闻存储数据(CoreData的使用,增删改查)的更多相关文章
- JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能
JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能 html <table id="productDg"></table> &l ...
- 通过Java代码实现对数据库的数据进行操作:增删改查
在写代码之前,依然是引用mysql数据库的jar包文件:右键项目-构建路径-设置构建路径-库-添加外部JAR 在数据库中我们已经建立好一个表xs :分别有xuehao xingming xue ...
- Python--day42--mysql操作数据库及数据表和基本增删改查
sql语法规则: 一.操作文件夹 1.创建数据库db2:create database db2; 2.创建数据库db2并标明数据库的编码格式为utf8:create database db2 defa ...
- Django ORM 实现数据的多表 增删改查
一.创建模型和表 假定下面这些概念.字段与关系: 作者模型:一个作者有姓名和年龄. 作者详细模型:把作者的详情放到详情表,手机号,家庭住址信息. 作者详情模型 和 作者模型之间是一对一的关系(one- ...
- Django ORM 实现数据的单表 增删改查
一.配置环境 1 Django 连接数据库(MySQL) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME' ...
- MFC中对基于ODBC对数据ACCESS数据库的增删改查。
在MFC中可以使用很多方法对数据库进行操作. 什么ODBC 什么ADO之类的,这里要介绍使用的ODBC这种方法,通过本文的阅读可以达初步掌握在MFC里面通过ODBC访问ACCESS数据库. 涉及到的 ...
- CoreData 从入门到精通(二) 数据的增删改查
在上篇博客中,讲了数据模型和 CoreData 栈的创建,那下一步就是对数据的操作了.和数据库一样,CoreData 里的操作也无非是增删改查.下面我们将逐步讲解在 CoreData 中进行增删改查的 ...
- CoreData的简单使用(二)数据的增删改查,轻量级的版本迁移
上一篇中我们已经使用CoreData创建了一个SQLite数据库 CoreData的简单使用(一)数据库的创建 现在对数据库进行数据的CRUD(增删改查) 1.Data Model 的设置 创建一个D ...
- iOS界面-仿网易新闻左侧抽屉式交互 续(添加新闻内容页和评论页手势)
本文转载至 http://blog.csdn.net/totogo2010/article/details/8637430 1.介绍 有的博友看了上篇博文iOS界面-仿网易新闻左侧抽屉 ...
随机推荐
- MyEclipse 死掉,JVM terminated. Exit code=1073807364
刚入手的新成员,刚开始使用myeclipse,是不是会有一大堆的问题,然后没有目标的走,这里有个小技巧,那就是如果做项目出现问题,一定要自己现在网络搜寻答案,网络时代.技术时代走到现在,一定有他的道理 ...
- 深入了解webservice_概念总结
最近公司需要对java web端的第三方接口进行测试,使用WebService+TestNG实现,TsetNg是常用的自动化测试框架,这就不介绍了. WebService是一种跨编程语言和跨操作系统平 ...
- yii2的windows下安装及前期步骤
Yii2的安装(以生成basic目录为例) 第一步:服务器安装好后生成www目录,在该目录下新建yii2目录,把下载的compser.phar包放在该目录下 第二步:dos命令下进入项目目录 第三步: ...
- Thinking In Java 读书笔记
面向对象语言,五个基本特性: 1)万物皆为对象. 2)程序是对象的集合,他们通过发送消息来告知彼此所要做的. 3)每个对象都有自己的由其他对象所构成的存储. 4)每个对象都拥有其类型.即:每个对象都是 ...
- 2014.12.05(解决eclipse的adb打不开)
一.问题如下图所示 The connection to adb is down, and a severe error has occured.You must restart adb and Ecl ...
- laravel 目录结构
图 1.1 显示了 Laravel 项目目录结构是什么样子: 图1.1 Laravel 项目目录结构 就如你看到这样,laravel下面只包含了4个文件夹,这4个文件夹下面有一些子文件夹,这种丰富的子 ...
- MySQL存储过程循环添加数据
经常需要测试数据,写个存储过程方便日后使用. DROP PROCEDURE IF EXISTS add_member; DELIMITER $$ CREATE PROCEDURE add_member ...
- Python精神
[root@LDAP_slave ~]# python -c "import this" The Zen of Python, by Tim Peters Beautiful is ...
- C#:只运行一个程序
一.通过系统事件 1.实现如下: using System; using System.Collections.Generic; using System.Linq; using System.Tex ...
- C#.Net理论
-------------2014年8月28---------------------------- 1.C#的委托是什么,事件是不是一种委托?答:委托可以把一个方法作为参数代入另一个方法.委托可以理 ...