CoreData在开发中的应用

创建篇(方式一、方式二)


方式一:手动创建CoreData模板

步骤一.新建CoreData模板

CoreData在开发中的应用_第1张图片
One.png

步骤二.创建表

CoreData在开发中的应用_第2张图片
Two.png
CoreData在开发中的应用_第3张图片
Three.png
CoreData在开发中的应用_第4张图片
Four.png

修改表名

CoreData在开发中的应用_第5张图片
修改表名.png

方式二:自动创建CoreData模板

步骤一.新建项目时勾选coreData

CoreData在开发中的应用_第6张图片
勾选coreData.png

步骤二.创建CoreData模板成功

CoreData在开发中的应用_第7张图片
查看.png

使用篇

不解释,直接上部分代码,代码来自互联网,如有侵权,提醒删之

  • ViewController.m文件
#import "ViewController.h"
#import "JSONKit.h"
#import "CoreDateManager.h"
#import "NewsCell.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *newsTableView;
@property (nonatomic, strong) NSMutableArray *resultArray;
@end

@implementation ViewController{
    
    CoreDateManager *coreManager;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"%@",NSHomeDirectory());
    coreManager = [[CoreDateManager alloc]init];
    
    //更新时间   从NSUserDefaults中读取updateDate这个key对应的value
    NSString *updateDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"updateDate"];
    
    if (!updateDate) {//如果无此对象(没有"updateDate"这个key),表示第一次,那么就读数据(数据来自服务器或者本地的plist文件)写到数据库中
        [self writeDate];
        
    }else{
        //有此对象说明只要从数据库中(NSUserDefaults的存储路径)读数据
        NSTimeInterval update = updateDate.doubleValue;
        NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
        //8小时一更新
        if ((now - update)>8*60*60) {
            //如果超出八小时就把数据库清空再重新写
            [coreManager deleteData];
            [self writeDate];
        }else{
            //没有超过8小时就从数据库中读
            NSMutableArray *array = [coreManager selectData:10 andOffset:0];
            self.resultArray = [NSMutableArray arrayWithArray:array];
            [self.newsTableView reloadData];
        }
    }
    
    
}
-(void)writeDate
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate timeIntervalSinceReferenceDate]] forKey:@"updateDate"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //读取信息,我在这里写成本地的了,一般的都是从网上获取数据
    NSString *path = [[NSBundle mainBundle]pathForResource:@"News" ofType:@"txt"];
    NSString *data = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    // json数据解析成数组
    NSArray *array = [data objectFromJSONString];
    //    NSLog(@"%@",array);
    self.resultArray = [NSMutableArray arrayWithCapacity:array.count];
    // 遍历数组中的每一个对象,每一个对象都是字典,用dict表示
    for (NSDictionary *dict in array) {
        // 手写initWithDictionary:方法进行字典转模型
        News *info = [[News alloc]initWithDictionary:dict];
        // 将每一个模型存储到可变数组self.resultArray中。self.resultArray就是平时所说的模型数组
        [self.resultArray addObject:info];
    }
    //    NSLog(@"%@",self.resultArray);
    
    //把数据(模型数组)写到数据库
    [coreManager insertCoreData:self.resultArray];
    // 刷新newsTableView
    [self.newsTableView reloadData];
}

#pragma UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NewsCell";
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *cells = [[NSBundle mainBundle] loadNibNamed:@"NewsCell" owner:self options:nil];
        cell = [cells lastObject];
    }
    News *info = [self.resultArray objectAtIndex:indexPath.row];
    // 设置数据
    [cell setContent:info];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当你点击时说明要看此条新闻,那么就标注此新闻已被看过
    News *info = [self.resultArray objectAtIndex:indexPath.row];
    info.islook = @"1";
    //改变数据库查看状态
    [coreManager updateData:info.newsid withIsLook:@"1"];
    //改变resultarry数据
    [self.resultArray setObject:info atIndexedSubscript:indexPath.row];
    
}

@end
  • CoreDateManager.h和CoreDateManager.m文件
#import 
#import "News.h"
#import 
//  必须和ZbModel.xcdatamodeld文件的News表的表名一致。否则当TableName作为entityForName:方法的参数时,由于找不到此表程序就会崩溃
#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





#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
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    // 加载ZbModel表
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ZbModel" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    // 必须为ZbModel.sqlite,数据都存在了ZbModel.sqlite文件。若为别的文件,则cell上显示不出数据,因为数据源为空。
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ZbModel.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.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//插入数据
- (void)insertCoreData:(NSMutableArray*)dataArray
{
    NSManagedObjectContext *context = [self managedObjectContext];
    // 遍历数组中的每一个元素,每一个元素都是模型,用info表示。以后可以通过info方法模型中的属性
    for (News *info in dataArray) {
        // NSEntityDescription:描述一种抽象数据类型,相当于数据库中的一个表
        News *newsInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];
        // 将遍历出来的newsid属性赋值给等号左侧的newsid
        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];
    // entityForName的参数必须为ZbModel.xcdatamodeld文件的表名,否则程序会因为找不到这个表名而崩溃。
    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])// datas中有数据且没有错误
    {
        for (NSManagedObject *obj in datas)// 遍历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
  • 数据源:News.txt文件
[
    {
        "id": "1",
        "title": "明星双11也疯狂晒单晒幸福",
        "descr": "一起来看看明星们是如何度过光棍节这个疯狂的日子吧",
        "imgurl": "http://img1.cache.netease.com/lady/2013/11/12/2013111209141859623.jpg"
    },
    {
        "id": "2",
        "title": "\"代码女神\"脱俗 成最美程序员",
        "descr": "\"代码女神\"美貌惊人,她竟然是个程序员",
        "imgurl": "http://img3.cache.netease.com/lady/2013/11/12/201311120830507ac45.jpg"
    },
    {
        "id": "3",
        "title": "黄菡:安全感源于强大的内心",
        "descr": "现代女性首先一定要自立,能够有独立的思想能力。",
        "imgurl": "http://img2.cache.netease.com/lady/2013/11/12/20131112084431b6aee.jpg"
    },
    {
        "id": "4",
        "title": "女王范冰冰穿衣造型变懒惰",
        "descr": "范冰冰这位造型女王近来变得十分\"懒惰\"。",
        "imgurl": "http://img6.cache.netease.com/lady/2013/11/12/2013111209111471ed4.jpg"
    },
    {
        "id": "5",
        "title": "应采儿产后首拍封面大片",
        "descr": "应采儿产后首拍封面大片,尽显迷人气质。",
        "imgurl": "http://img4.cache.netease.com/lady/2013/11/12/201311120829029cc3a.jpg"
    },
    {
        "id": "6",
        "title": "张亮父子示范型男亲子装",
        "descr": "惹人爱亲子装系列,今天小编盘点张亮父子的时尚型男亲子装。",
        "imgurl": "http://img3.cache.netease.com/lady/2013/11/12/201311120904577c9a0.jpg"
    },
    {
        "id": "7",
        "title": "本14岁清纯萝莉走红网络",
        "descr": "日本14岁清纯萝莉走红网络,外表清纯可爱。",
        "imgurl": "http://img1.cache.netease.com/lady/2013/11/12/20131112083235f5b8b.jpg"
    },
    {
        "id": "8",
        "title": "石头诗龄学包饺子 王岳伦刷碗",
        "descr": "近日,王诗龄和石头在郭涛的指导下包出的饺子有模有样。",
        "imgurl": "http://img2.cache.netease.com/lady/2013/11/12/20131112091709fa3dc.jpg"
    },
    {
        "id": "9",
        "title": "MTV音乐大奖 李宇春战袍加身",
        "descr": "美国,万人瞩目的MTV欧洲音乐大奖举行。",
        "imgurl": "http://img4.cache.netease.com/lady/2013/11/12/20131112090132f4647.jpg"
    },
    {
        "id": "10",
        "title": "吴奇隆公开承认与刘诗诗恋情",
        "descr": "发微博称\"很珍惜這份得之不易的感情\",刘诗诗予以转发。",
        "imgurl": "http://img4.cache.netease.com/3g/2013/11/13/2013111302215625fea.jpg"
    }
]

效果篇

CoreData在开发中的应用_第8张图片
101.150.gif

[LS](https://pan.baidu.com/s/1i518aRr 密码: qfh7)

你可能感兴趣的:(CoreData在开发中的应用)