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界面-仿网易新闻左侧抽屉 ...
随机推荐
- jboss-as 目录结构(转)
jboss-as 目录结构(Directory Structure) Directory Description bin Contains startup, shutdown and other sy ...
- AMD机制与cMD的区别和概念简要介绍
1.http://www.cnblogs.com/dojo-lzz/p/4707725.html 2.http://blog.chinaunix.net/uid-26672038-id-4112229 ...
- 怎样查出SQLServer的性能瓶颈
怎样查出SQLServer的性能瓶颈 --王成辉翻译整理,转贴请注明出自微软BI开拓者[url]www.windbi.com[/url]--原帖地址 如果你曾经做了很长时间的DBA,那么你会了解到SQ ...
- 161124、Java 异常处理的误区和经验总结
本文着重介绍了 Java 异常选择和使用中的一些误区,希望各位读者能够熟练掌握异常处理的一些注意点和原则,注意总结和归纳.只有处理好了异常,才能提升开发人员的基本素养,提高系统的健壮性,提升用户体验, ...
- 160914、ionic指令简单布局
1) 添加引用类库(ionic样式和ionic js文件) 2) 标题栏,页脚栏,内容区 3) Js引入ionic类库,添加页面操作方法和对象 4) 数据初始化 5) Html页面绑定方法和对象 &l ...
- Microsoft JET Database Engine (0x80004005)
解决方法:打开我的电脑,菜单栏工具选项下去掉打钩查看卡里使用简单文件共享(推荐)这项. 找到windows/temp文件夹,对temp右键属性,安全选项里添加everyone这个用户,选择完全控制权限 ...
- 怎样用PHP制作验证码呢?
生成验证码无非就那么几个步骤,首先是获取一个随机字符串,然后创建一个布画,将生成的字符串写到布画上,我们还可以在布画上画线画雪花,现在帖一段生成验证码的代码. 源代码: <?phpsession ...
- php中的curl】php中curl的详细解说
本文我来给大家详细介绍下cURL的简单的使用方法,下文我将会给大家详细介绍cURL的高级应用, cURL可以使用URL的语法模拟浏览器来传输数据, FTP, FTPS, HTTP, HTTPS, GO ...
- Oracle中左右外连接详解
数据表的连接有: 1.内连接(自然连接): 只有两个表相匹配的行才能在结果集中出现 2.外连接: 包括 (1)左外连接(左边的表不加限制) (2)右外连接(右边的表不加限制) (3)全外连接(左右两 ...
- Codeforces Round #337 Vika and Segments
D. Vika and Segments time limit per test: 2 seconds memory limit per test: 256 megabytes input ...