`
knight_black_bob
  • 浏览: 855083 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

iOS coredata 使用

    博客分类:
  • ios
阅读更多

 



 

 

 

 

//
//  AppDelegate.h
//  IteyeBlog
//
//  Created by youbao on 16/9/24.
//  Copyright © 2016年 youbao. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;


@end

 

//
//  AppDelegate.m
//  IteyeBlog
//
//  Created by youbao on 16/9/24.
//  Copyright © 2016年 youbao. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //TODO:
    
    
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.curiousby.baoyou.cn.IteyeBlog" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"IteyeBlog" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"IteyeBlog.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this 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();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = 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();
        }
    }
}

@end

 

//
//  ViewController.m
//  IteyeBlog
//
//  Created by youbao on 16/9/24.
//  Copyright © 2016年 youbao. All rights reserved.
//

#import "ViewController.h"
#import "AFHTTPSessionManager.h"
#import   "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "OfferDBEntity.h"

static NSString *const IconUrl = @"http://ods5pg0qp.bkt.clouddn.com/iteyeblog/icon.png";




@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *btn;
@property (weak, nonatomic) IBOutlet UIImageView *image;


@property (weak, nonatomic) IBOutlet UIButton *addLable;
@property (weak, nonatomic) IBOutlet UIButton *selectLable;
@property (weak, nonatomic) IBOutlet UIButton *updateLable;
@property (weak, nonatomic) IBOutlet UIButton *delLable;

@property(nonatomic,retain) AppDelegate* appDelegate;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(IBAction) add:(id)sender{

    OfferDBEntity *entity = (OfferDBEntity *)
    [NSEntityDescription insertNewObjectForEntityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
    
    entity.iconurl = IconUrl;
    entity.name = @"baoyou it";
    entity.desc = @"IT 工程师";
    
    NSError* error;
    BOOL isSaveSuccess=[self.appDelegate.managedObjectContext save:&error];
    if (!isSaveSuccess) {
        NSLog(@"Error:%@",error);
    }else{
        NSLog(@"Save successful!");
    }
    
}
-(IBAction) select:(id)sender{

    
    NSFetchRequest* request=[[NSFetchRequest alloc] init];
    NSEntityDescription* entity=[NSEntityDescription entityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
    [request setEntity:entity];
    NSError* error=nil;
    NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResult==nil) {
        NSLog(@"error:%@",error);
    }
    NSLog(@"the count of entity: %ld",[mutableFetchResult count]);
    for (OfferDBEntity *entity in mutableFetchResult) {
        NSLog(@"iconrl=%@,name=%@,desc=%@",entity.iconurl,entity.name ,entity.desc);
    }
    
}
-(IBAction) update:(id)sender{

    NSFetchRequest* request=[[NSFetchRequest alloc] init];
    NSEntityDescription* user=[NSEntityDescription entityForName:@"OfferDBEntity"  inManagedObjectContext:self.appDelegate.managedObjectContext];
    [request setEntity:user];
    //查询条件
    NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"baoyou it"];
    [request setPredicate:predicate];
    NSError* error=nil;
    NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResult==nil) {
        NSLog(@"error:%@",error);
    }
    NSLog(@"the count of entity: %ld",[mutableFetchResult count]);
    //更新age后要进行保存,否则没更新
    for (OfferDBEntity *entity in mutableFetchResult) {
        [entity setDesc: @"baoyou desc"];
    }
    [self.appDelegate.managedObjectContext save:&error];
}
-(IBAction) del:(id)sender{

    NSFetchRequest* request=[[NSFetchRequest alloc] init];
    NSEntityDescription* user=[NSEntityDescription entityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
    [request setEntity:user];
    NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"baoyou it"];
    [request setPredicate:predicate];
    NSError* error=nil;
    NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResult==nil) {
        NSLog(@"Error:%@",error);
    }
    NSLog(@"The count of entry: %ld",[mutableFetchResult count]);
    for (OfferDBEntity *entity in mutableFetchResult) {
        [self.appDelegate.managedObjectContext deleteObject:entity];
    }
    
    if ([self.appDelegate.managedObjectContext save:&error]) {
        NSLog(@"Error:%@,%@",error,[error userInfo]);
    }
}





@end

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

 

 

  • 大小: 156.6 KB
分享到:
评论

相关推荐

    ios CoreData使用(封装)

    本教程将深入探讨如何在iOS应用中使用CoreData进行数据持久化,并对其进行了封装,以便更高效、简洁地实现增删改查操作。 首先,CoreData的核心概念包括实体(Entity)、属性(Attribute)、关系(Relationship)和...

    IOS coredata使用

    在iOS开发中,CoreData是苹果提供的一种强大的数据管理框架,用于实现本地数据持久化。相比SQLite3,CoreData提供了更高层次的抽象,使得开发者能够更便捷地处理数据模型、对象关系以及数据存储。本篇文章将详细介绍...

    IOS CoreData使用

    本篇文章将深入探讨如何在iOS应用中使用CoreData。 ### 1. CoreData简介 CoreData并非数据库系统,而是基于模型-视图-控制器(MVC)架构的框架,用于管理应用程序的“数据模型”。它提供了对象的持久化,可以将...

    iOS CoreData 的小Demo

    **正文** iOS的CoreData是苹果提供的一种强大的数据管理框架,用于在应用程序中存储、管理和检索数据。这个“iOS CoreData的小Demo”是一个很好...通过学习和实践,你将能够熟练地在iOS应用中使用CoreData来管理数据。

    IOS coreData

    coreData的使用教程,引擎下,有一个带有read属性的Article实体。把所有条目标记为已读,程序需要加载这个feed的所有文章(可能通过一对多的关系),然后设置read属性为YES。 大部分情况下这样没关系。但是设想那个...

    iOS CoreData 数据迁移操作底板

    在iOS应用开发中,CoreData是苹果提供的一种强大的对象图管理器,用于处理应用程序的数据模型。数据迁移是当数据模型发生变化时,确保旧版本的数据能够顺利迁移到新模型中的过程。这个“iOS CoreData 数据迁移操作...

    iOS coredata 简单使用

    以下是对Core Data在iOS应用中简单使用的详细说明。 1. **Core Data架构** Core Data 包含多个组件,如 Managed Object Model (MOM)、Managed Object Context (MOC) 和 Persistent Store Coordinator (PSC)。MOM ...

    iOS CoreData 增 删 改 查 demo

    在iOS应用开发中,CoreData是一个非常重要的框架,它提供了对象关系映射(ORM)功能,使得开发者可以方便地管理应用程序的数据模型。本教程通过一个简单的"增删改查"(CRUD)DEMO,深入讲解如何利用CoreData在iOS...

    ios-coredata简单封装.zip

    "ios-coredata简单封装.zip" 文件显然包含了一个简化Core Data使用流程的封装库或代码示例,旨在帮助开发者更高效地进行增删改查操作。 1. **建表(创建实体)**: 在Core Data中,"表"被称为实体(Entity)。创建...

    ios-CoreData添加、删除数据,聊天记录式分页查询.zip

    本项目"ios-CoreData添加、删除数据,聊天记录式分页查询.zip"主要关注了如何利用CoreData在iOS应用中实现数据的添加、删除操作,以及聊天记录式的分页查询。 首先,我们要理解CoreData的基本架构。CoreData由模型...

    iOS本地数据库Sqlite(FMDB)及CoreData的使用

    下面我们将深入探讨这两者,并结合FMDB,一个Objective-C的SQLite库,来讲解它们在iOS中的使用。 首先,SQLite是一种开源的、自包含的、无服务器的、类型的SQL数据库引擎。它的优点在于小巧、高效且兼容性强,适用...

    iOS CoreData实现简易的成绩管理系统

    在iOS应用开发中,CoreData是一个强大的框架,用于管理应用程序的模型层对象和数据持久化。这个教程将向你展示如何使用CoreData来构建一个简易的成绩管理系统,通过表视图来实现成绩的增删查改功能。以下是关于...

    iOS CoreData and Sqlite3 Demo

    在iOS开发中,CoreData和SQLite3是两种常见的数据存储技术。它们各有特点,适用于不同的应用场景。本Demo旨在展示如何在iOS应用中使用这两种技术,包括数据管理、用户交互以及正则表达式的应用。 首先,CoreData是...

    ios CoreData demo

    这个“ios CoreData demo”项目是一个很好的起点,帮助新手了解 CoreData 的基本工作原理和使用方式。通过实践这个 demo,你可以逐步掌握如何在实际应用中有效地运用 CoreData 来管理数据。记得参考链接中的教程,...

    IOS之分析网易新闻存储数据 CoreData的使用 增删改查

    本篇文章将深入探讨如何在iOS应用中使用CoreData进行数据的增删改查操作,并结合实例——分析网易新闻的存储数据来阐述其工作原理。 首先,让我们了解CoreData的基本概念。CoreData不是一个数据库,而是一个对象图...

    iOS CoreData基本架构类

    CoreDataDAO继承于NSObject,作为一个基本的model; CoreDataDAO中含有managedObjectModel、managedObjectContext、persistentStoreCoordinator等基本类和方法,方便其子类调用 NoteDao继承于CoreDataDAO,执行Note...

    ios-CoreData 增删改查.zip

    简单实现了对数据的增删改查,都有注释,另外我还写了一篇简书,特别详细,简单粗暴,是人都看懂~~~ 简书: http://www.jianshu.com/p/7c1ac5ce614b github: https://github.com/ty82885279/CoreData

    CoreData iOS

    4. **数据变更管理**:CoreData使用上下文(Context)来管理数据的变更。当数据发生变化时,可以先在内存中的上下文进行修改,然后在合适的时候再提交到持久化存储。 5. **事务处理**:CoreData支持事务,确保数据...

    ios coredata demo

    这个"ios coredata demo"项目旨在为初学者和其他开发者提供一个实践和理解Core Data的平台。通过这个项目,我们可以深入学习如何在iOS应用中使用Core Data进行数据存储和检索。 1. **Core Data架构** Core Data ...

Global site tag (gtag.js) - Google Analytics