`

iPhone开发数据持久化总结之第5篇—CoreData技术 .

    博客分类:
  • ios
ios 
阅读更多
实现的功能:1)演示使用CoreData持久化数据(仅显示基本操作,不包括很多复杂的操作)。

关键词:数据持久化 CoreData




1、新建一空工程,命名为:Persistence_CoreData:
[img]

[/img]

[img]

[/img]







2、选中“Use Core Data”后创建的工程中,AppDelegate.h中多了三个property,如下:
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

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

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

@end

代码解释
//备注1
NSManagedObjectContext:相当于数据库操作
NSManagedObjectModel:相当于数据库中的表及它们之间的关系
persistentStoreCoordinator:相当于数据库存放方式
以上比较不一定准确,但是可以更容易理解CoreData的应用。






3、AppDelegate.m中多了三个方法,如下:
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    //设置根视图控制器
    self.window.rootViewController = [[ViewController alloc]initWithNibName:@"ViewController" bundle:nil];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    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
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (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();
        } 
    }
}

//备注2

#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:@"Persistence_CoreData" 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:@"Persistence_CoreData.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        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];
}

@end


//备注2
//这三个方法,对应返回备注1中声明的3个变量






4、新建视图控制器ViewController(带xib)
[img]

[/img]

修改AppDelegate.m中- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
设置根视图控制器









5、修改ViewController.xib,如下:
[img]

[/img]










6、修改Persistence_CoreData.xcdatamodeld,添加Entity,名称为User,如下
[img]

[/img]








7、修改ViewController,ViewController.h如下:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface ViewController : UIViewController{
    AppDelegate *appDelegate;
}

@property(strong,nonatomic)IBOutlet UITextField *serverIp;
@property(strong,nonatomic)IBOutlet UITextField *userName;
@end


ViewController.m如下:

#import "ViewController.h"
#import "AppDelegate.h"

@interface ViewController ()

@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //获取App代理
    appDelegate = [[UIApplication sharedApplication] delegate];
    
    //订阅通知
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    
    [self loadData];
}

//加载数据
-(void)loadData{
    //1)获取托管对象上下文(相当于数据库操作)
    NSManagedObjectContext *context = [appDelegate managedObjectContext];//备注3
    //2)创建NSFetchRequest对象(相当于数据库中的SQL语句)
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //3)创建查询实体(相当于数据库中要查询的表)
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    //设置查询实体
    [request setEntity:entityDescription];
    //4)创建排序描述符,ascending:是否升序(相当于数据库中排序设置)。此处仅为演示,本实例不需要排序
    NSSortDescriptor *sortDiscriptor = [[NSSortDescriptor alloc] initWithKey:@"userName" ascending:NO];
    NSArray *sortDiscriptos = [[NSArray alloc] initWithObjects:sortDiscriptor, nil];
    [request setSortDescriptors:sortDiscriptos];
    //5)创建查询谓词(相当于数据库中查询条件) 此处仅为演示,本实例不需要查询条件
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(serverIp like %@)",@"192"];
    [request setPredicate:pred];
    
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    if(objects == nil){
        NSLog(@"There has a error!");
        //做错误处理
    }else{
        if([objects count]>0){
            NSManagedObject *oneObject = [objects objectAtIndex:0];
            NSString *serverIp = [oneObject valueForKey:@"serverIp"];
            NSString *userName = [oneObject valueForKey:@"userName"];
            self.serverIp.text = serverIp;
            self.userName.text = userName;
        }    
    }
}

//应用界面退出时,保存数据
-(void)applicationWillResignActive:(NSNotification *)notification{
    NSLog(@"applicationWillResignActive");
    //创建托管对象上下文
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    [request setEntity:entityDescription];
    
    NSManagedObject *user = nil;
    NSError *error;
    NSArray *objets = [context executeFetchRequest:request error:&error];
    if(objets==nil){
        NSLog(@"There has a error!");
        //做错误处理
    }
    
    if([objets count]>0){
        //非第一次,更新数据
        NSLog(@"更新操作");
        user = [objets objectAtIndex:0];
    }else{
        NSLog(@"插入操作");
        //第一次保存,插入新数据
        user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
    }
    
    [user setValue:self.serverIp.text forKeyPath:@"serverIp"];
    [user setValue:self.userName.text forKeyPath:@"userName"];
    
    [context save:&error];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


//备注3
//通过 delegate调用方法managedObjectContext,得到NSManagedObjectContext对象,
//NSManagedObjectContext对象会跟NSPersistentStoreCoordinator对象交互,NSPersistentStoreCoordinator对象负责处理底层的存储,sqlite3数据库名称默认为工程名称,Persistence_CoreData.sqlite





8、CoreData使用的数据库存储的位置是:
/Users/duobianxing/Library/Application Support/iPhone Simulator/5.0/Applications/BCCE1DDC-F50F-4A52-9678-991AC6DFBC7C/Documents
[img]

[/img]




虽然该博文演示的创建“Use Core Data”的工程,其实只要搞明白选中“Use Core Data”后该工程模板都添加了哪些内容以及其作用?那么在一个已存在的工程(没有使用CorData)的加入CoreData的支持也非常方便。
  • 大小: 182.7 KB
  • 大小: 191.5 KB
  • 大小: 197.6 KB
  • 大小: 105.3 KB
  • 大小: 93.8 KB
  • 大小: 74.5 KB
分享到:
评论

相关推荐

    使用CoreData开发iPhone手机应用软件的实例教程.pdf

    《使用CoreData开发iPhone手机应用软件的实例教程》是一份专为初学者设计的详细教程,旨在引导读者通过实例学习如何使用Core Data在iPhone应用中管理数据。Core Data是iOS平台上的一个本地数据管理框架,它并非传统...

    CoreData实例

    CoreData是苹果公司为其iOS和macOS平台提供的一项强大的数据管理框架,用于处理应用程序的持久化数据。这个“CoreData实例”项目显然旨在为初学者提供一个实践平台,通过一个实际的小型应用来演示如何使用CoreData...

    CoreData Programming Guide

    5. **持久化存储(Persistent Store)**:物理上存储数据的地方,可以是SQLite数据库、XML文件等多种形式。 6. **持久化协调器(Persistent Store Coordinator)**:管理多个持久化存储之间的关系,协调数据的同步。 ##...

    iphone开发常用代码

    5. **数据持久化** CoreData是Apple提供的数据管理框架,用于存储和检索对象。SQLite或 Realm 也是常见的数据持久化选择,尤其适合需要进行复杂查询的应用。 6. **通知(Notification)** 使用`...

    iphone3 开发秘籍 例程2

    6. **C19-CoreData**:Core Data是苹果的持久化框架,用于管理应用程序的数据模型。这一章将涵盖实体关系设计、数据模型创建、数据存储与检索,以及事务处理和错误处理机制。 7. **C20-StoreKit**:StoreKit是用于...

    iPhone 开发基础教程 Beginning iOS 6 Development Exploring the iOS SDK

    - 涉及iOS中的数据存储方式,包括使用属性列表(Plist)、SQLite数据库、CoreData框架进行数据持久化。 #### 第14章:嘿!你!上iCloud! - 介绍如何利用iCloud为应用提供云端备份和数据同步的功能,包括使用...

    iphone开发秘籍

    4. **数据管理(C19-CoreData)**:CoreData是Apple的数据持久化框架,用于存储和管理对象图。它提供了一种模型驱动的方法来处理数据,支持关系型数据模型,并可以自动处理数据的保存和加载。CoreData包括实体...

    Core Data By Tutorials 最新swift版

    1. 标题中提到的“CoreData”,是iOS开发中用于数据持久化的核心技术,通过它可以轻松地创建、查询、更新和删除应用中的数据。 2. 描述中提到的“By Tutorials”,意味着本书采用的是循序渐进的教程形式,通过实际...

    iphone实现聊天功

    - `CoreData`是Apple提供的对象关系映射框架,用于持久化应用数据,如用户的聊天记录。 - 如果需要云存储,可以使用iCloud或者第三方服务如Firebase,以便用户在不同设备间同步聊天数据。 4. **消息处理**: - ...

    ios应用源码之火车余票查询 for iphone3 2018128

    8. **数据持久化**:为了保存用户的查询历史或偏好设置,应用可能使用UserDefaults进行轻量级的数据存储,或者使用CoreData进行更复杂的关系型数据管理。 9. **错误处理**:良好的错误处理机制是确保应用稳定运行的...

    开发文档iOS.5

    ### 开发文档iOS 5 知识点概览 ...通过上述章节内容的详细介绍,本书不仅为初学者提供了iOS 5开发的基础知识,还涵盖了从界面设计到数据持久化的方方面面,旨在帮助读者全面了解iOS 5开发的核心技术和最佳实践。

    ios应用源码之一些iphone开源项目代码senseofmed 2018127

    5. **本地存储**: CoreData是Apple提供的一个强大的数据持久化框架,可以用来存储应用程序的数据。另一个常见选项是SQLite数据库。源码中可能会有这两种方式的使用示例。 6. **通知与代理**: iOS中的Notification和...

    ios-高仿美团框架.zip

    - CoreData:苹果提供的持久化框架,用于存储应用数据。在高仿美团框架中,可能用于保存用户的偏好设置、订单信息等。 - Realm:另一种流行的持久化解决方案,比CoreData更轻量级,操作更加灵活,性能优秀。 - ...

    IOS.6.IN.PRATICE

    - **内容**: 讲解如何利用CoreData进行数据持久化,同时实现与iPod库的交互以播放音乐。 - **第8章**: ... #### 五、总结 - 《iOS in Practice》是一本面向实际应用的iOS开发指南,通过丰富的案例和详细的步骤指导...

    Beginning.iOS.5.Development

    **自动旋转与自动调整大小**(第5章) - **章节概要**:介绍如何让应用适应不同的设备屏幕尺寸和方向变化。 - **重点内容**: - 屏幕方向感知。 - Auto Layout布局系统。 - Autoresizing约束。 6. **多视图...

    iOS5开发基础教程(高清PDF)

    ##### 第5章:自动旋转与自动缩放 - **知识点**: - 屏幕方向变化时自动旋转视图的技术细节。 - Auto Layout布局系统的概念与实践。 - 如何利用Auto Layout实现不同屏幕尺寸下的适应性布局。 - 适配多种设备...

    iphone笔试题和面试题

    5. **数据持久化**:包括NSUserDefaults、SQLite数据库、CoreData的使用,以及文件系统操作。 6. **网络编程**:熟悉HTTP/HTTPS请求,使用URLSession或第三方库如Alamofire进行网络请求,理解异步编程和JSON解析。 ...

Global site tag (gtag.js) - Google Analytics