用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的。

首先:

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介绍参考官方:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdTechnologyOverview.html#//apple_ref/doc/uid/TP40009296-SW1

接下来是如何创建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:

  1. #import <Foundation/Foundation.h>
  2. #import "News.h"
  3. #define TableName @"News"
  4. @interface CoreDateManager : NSObject
  5. @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
  6. @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
  7. @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
  8. - (void)saveContext;
  9. - (NSURL *)applicationDocumentsDirectory;
  10. //插入数据
  11. - (void)insertCoreData:(NSMutableArray*)dataArray;
  12. //查询
  13. - (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage;
  14. //删除
  15. - (void)deleteData;
  16. //更新
  17. - (void)updateData:(NSString*)newsId withIsLook:(NSString*)islook;
  18. @end

以下是.m的实现:

  1. //
  2. //  CoreDateManager.m
  3. //  SQLiteTest
  4. //
  5. //  Created by rhljiayou on 14-1-8.
  6. //  Copyright (c) 2014年 rhljiayou. All rights reserved.
  7. //
  8. #import "CoreDateManager.h"
  9. @implementation CoreDateManager
  10. @synthesize managedObjectContext = _managedObjectContext;
  11. @synthesize managedObjectModel = _managedObjectModel;
  12. @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
  13. - (void)saveContext
  14. {
  15. NSError *error = nil;
  16. NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
  17. if (managedObjectContext != nil) {
  18. if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
  19. // Replace this implementation with code to handle the error appropriately.
  20. // 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.
  21. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  22. abort();
  23. }
  24. }
  25. }
  26. #pragma mark - Core Data stack
  27. // Returns the managed object context for the application.
  28. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
  29. - (NSManagedObjectContext *)managedObjectContext
  30. {
  31. if (_managedObjectContext != nil) {
  32. return _managedObjectContext;
  33. }
  34. NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  35. if (coordinator != nil) {
  36. _managedObjectContext = [[NSManagedObjectContext alloc] init];
  37. [_managedObjectContext setPersistentStoreCoordinator:coordinator];
  38. }
  39. return _managedObjectContext;
  40. }
  41. // Returns the managed object model for the application.
  42. // If the model doesn't already exist, it is created from the application's model.
  43. - (NSManagedObjectModel *)managedObjectModel
  44. {
  45. if (_managedObjectModel != nil) {
  46. return _managedObjectModel;
  47. }
  48. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"NewsModel" withExtension:@"momd"];
  49. _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  50. return _managedObjectModel;
  51. }
  52. // Returns the persistent store coordinator for the application.
  53. // If the coordinator doesn't already exist, it is created and the application's store added to it.
  54. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
  55. {
  56. if (_persistentStoreCoordinator != nil) {
  57. return _persistentStoreCoordinator;
  58. }
  59. NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"NewsModel.sqlite"];
  60. NSError *error = nil;
  61. _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  62. if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
  63. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  64. abort();
  65. }
  66. return _persistentStoreCoordinator;
  67. }
  68. #pragma mark - Application's Documents directory
  69. // Returns the URL to the application's Documents directory.获取Documents路径
  70. - (NSURL *)applicationDocumentsDirectory
  71. {
  72. return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  73. }
  74. //插入数据
  75. - (void)insertCoreData:(NSMutableArray*)dataArray
  76. {
  77. NSManagedObjectContext *context = [self managedObjectContext];
  78. for (News *info in dataArray) {
  79. News *newsInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];
  80. newsInfo.newsid = info.newsid;
  81. newsInfo.title = info.title;
  82. newsInfo.imgurl = info.imgurl;
  83. newsInfo.descr = info.descr;
  84. newsInfo.islook = info.islook;
  85. NSError *error;
  86. if(![context save:&error])
  87. {
  88. NSLog(@"不能保存:%@",[error localizedDescription]);
  89. }
  90. }
  91. }
  92. //查询
  93. - (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage
  94. {
  95. NSManagedObjectContext *context = [self managedObjectContext];
  96. // 限定查询结果的数量
  97. //setFetchLimit
  98. // 查询的偏移量
  99. //setFetchOffset
  100. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  101. [fetchRequest setFetchLimit:pageSize];
  102. [fetchRequest setFetchOffset:currentPage];
  103. NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];
  104. [fetchRequest setEntity:entity];
  105. NSError *error;
  106. NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
  107. NSMutableArray *resultArray = [NSMutableArray array];
  108. for (News *info in fetchedObjects) {
  109. NSLog(@"id:%@", info.newsid);
  110. NSLog(@"title:%@", info.title);
  111. [resultArray addObject:info];
  112. }
  113. return resultArray;
  114. }
  115. //删除
  116. -(void)deleteData
  117. {
  118. NSManagedObjectContext *context = [self managedObjectContext];
  119. NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];
  120. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  121. [request setIncludesPropertyValues:NO];
  122. [request setEntity:entity];
  123. NSError *error = nil;
  124. NSArray *datas = [context executeFetchRequest:request error:&error];
  125. if (!error && datas && [datas count])
  126. {
  127. for (NSManagedObject *obj in datas)
  128. {
  129. [context deleteObject:obj];
  130. }
  131. if (![context save:&error])
  132. {
  133. NSLog(@"error:%@",error);
  134. }
  135. }
  136. }
  137. //更新
  138. - (void)updateData:(NSString*)newsId  withIsLook:(NSString*)islook
  139. {
  140. NSManagedObjectContext *context = [self managedObjectContext];
  141. NSPredicate *predicate = [NSPredicate
  142. predicateWithFormat:@"newsid like[cd] %@",newsId];
  143. //首先你需要建立一个request
  144. NSFetchRequest * request = [[NSFetchRequest alloc] init];
  145. [request setEntity:[NSEntityDescription entityForName:TableName inManagedObjectContext:context]];
  146. [request setPredicate:predicate];//这里相当于sqlite中的查询条件,具体格式参考苹果文档
  147. //https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
  148. NSError *error = nil;
  149. NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组,你需要取出你要更新的那个obj
  150. for (News *info in result) {
  151. info.islook = islook;
  152. }
  153. //保存
  154. if ([context save:&error]) {
  155. //更新成功
  156. NSLog(@"更新成功");
  157. }
  158. }
  159. @end

此句:

  1. NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"NewsModel.sqlite"];

生成以后,你可以在Documents下面看到三个文件:

那么你可以打开NewsModel.sqlite文件看一下里面的表格:

Z_METADATA里面记录了一个本机的UUID。

Z_PRIMARYKEY里面是所有自己创建的表格的名字。

ZNEWS是自己创建的表格,打开里面就是我们的数据记录。

此外你需要了解查询时候需要正则表达式:(官方的)

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html

使用是只要:coreManager = [[CoreDateManageralloc]init];创建对象

增删改查:

  1. //增
  2. [coreManager insertCoreData:_resultArray];
  3. //删
  4. [coreManager deleteData];
  5. //改
  6. [coreManager updateData:info.newsid withIsLook:@"1"];
  7. //查
  8. [coreManager selectData:10 andOffset:0];</span>

具体实现看源码。

CoreData很强大,用起来很方便,是一个不错的存储数据的好方法。

ok!

IOS之分析网易新闻存储数据(CoreData的使用,增删改查)的更多相关文章

  1. JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能

    JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能 html <table id="productDg"></table> &l ...

  2. 通过Java代码实现对数据库的数据进行操作:增删改查

    在写代码之前,依然是引用mysql数据库的jar包文件:右键项目-构建路径-设置构建路径-库-添加外部JAR 在数据库中我们已经建立好一个表xs :分别有xuehao  xingming    xue ...

  3. Python--day42--mysql操作数据库及数据表和基本增删改查

    sql语法规则: 一.操作文件夹 1.创建数据库db2:create database db2; 2.创建数据库db2并标明数据库的编码格式为utf8:create database db2 defa ...

  4. Django ORM 实现数据的多表 增删改查

    一.创建模型和表 假定下面这些概念.字段与关系: 作者模型:一个作者有姓名和年龄. 作者详细模型:把作者的详情放到详情表,手机号,家庭住址信息. 作者详情模型 和 作者模型之间是一对一的关系(one- ...

  5. Django ORM 实现数据的单表 增删改查

    一.配置环境 1 Django 连接数据库(MySQL) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME' ...

  6. MFC中对基于ODBC对数据ACCESS数据库的增删改查。

    在MFC中可以使用很多方法对数据库进行操作. 什么ODBC  什么ADO之类的,这里要介绍使用的ODBC这种方法,通过本文的阅读可以达初步掌握在MFC里面通过ODBC访问ACCESS数据库. 涉及到的 ...

  7. CoreData 从入门到精通(二) 数据的增删改查

    在上篇博客中,讲了数据模型和 CoreData 栈的创建,那下一步就是对数据的操作了.和数据库一样,CoreData 里的操作也无非是增删改查.下面我们将逐步讲解在 CoreData 中进行增删改查的 ...

  8. CoreData的简单使用(二)数据的增删改查,轻量级的版本迁移

    上一篇中我们已经使用CoreData创建了一个SQLite数据库 CoreData的简单使用(一)数据库的创建 现在对数据库进行数据的CRUD(增删改查) 1.Data Model 的设置 创建一个D ...

  9. iOS界面-仿网易新闻左侧抽屉式交互 续(添加新闻内容页和评论页手势)

     本文转载至  http://blog.csdn.net/totogo2010/article/details/8637430       1.介绍 有的博友看了上篇博文iOS界面-仿网易新闻左侧抽屉 ...

随机推荐

  1. MyEclipse 死掉,JVM terminated. Exit code=1073807364

    刚入手的新成员,刚开始使用myeclipse,是不是会有一大堆的问题,然后没有目标的走,这里有个小技巧,那就是如果做项目出现问题,一定要自己现在网络搜寻答案,网络时代.技术时代走到现在,一定有他的道理 ...

  2. 深入了解webservice_概念总结

    最近公司需要对java web端的第三方接口进行测试,使用WebService+TestNG实现,TsetNg是常用的自动化测试框架,这就不介绍了. WebService是一种跨编程语言和跨操作系统平 ...

  3. yii2的windows下安装及前期步骤

    Yii2的安装(以生成basic目录为例) 第一步:服务器安装好后生成www目录,在该目录下新建yii2目录,把下载的compser.phar包放在该目录下 第二步:dos命令下进入项目目录 第三步: ...

  4. Thinking In Java 读书笔记

    面向对象语言,五个基本特性: 1)万物皆为对象. 2)程序是对象的集合,他们通过发送消息来告知彼此所要做的. 3)每个对象都有自己的由其他对象所构成的存储. 4)每个对象都拥有其类型.即:每个对象都是 ...

  5. 2014.12.05(解决eclipse的adb打不开)

    一.问题如下图所示 The connection to adb is down, and a severe error has occured.You must restart adb and Ecl ...

  6. laravel 目录结构

    图 1.1 显示了 Laravel 项目目录结构是什么样子: 图1.1 Laravel 项目目录结构 就如你看到这样,laravel下面只包含了4个文件夹,这4个文件夹下面有一些子文件夹,这种丰富的子 ...

  7. MySQL存储过程循环添加数据

    经常需要测试数据,写个存储过程方便日后使用. DROP PROCEDURE IF EXISTS add_member; DELIMITER $$ CREATE PROCEDURE add_member ...

  8. Python精神

    [root@LDAP_slave ~]# python -c "import this" The Zen of Python, by Tim Peters Beautiful is ...

  9. C#:只运行一个程序

    一.通过系统事件 1.实现如下: using System; using System.Collections.Generic; using System.Linq; using System.Tex ...

  10. C#.Net理论

    -------------2014年8月28---------------------------- 1.C#的委托是什么,事件是不是一种委托?答:委托可以把一个方法作为参数代入另一个方法.委托可以理 ...