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

    转载注明原创:http://blog.csdn.net/rhljiayou/article/details/18037729

  • 相关阅读:
    前端技术-PS切图
    Html5资料整理
    Html5知识体系
    Html知识体系
    C语言知识结构
    ASP.NET知识结构
    src和href的区别
    Ajax的简单使用
    学习理论
    求模运算法则
  • 原文地址:https://www.cnblogs.com/xukunhenwuliao/p/3576238.html
Copyright © 2020-2023  润新知