当前位置: 代码迷 >> Iphone >> iPhone开发数据持久化小结之第5篇—CoreData技术
  详细解决方案

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

热度:81   发布时间:2016-04-25 06:05:22.0
iPhone开发数据持久化总结之第5篇—CoreData技术 .
实现的功能: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的支持也非常方便。
  相关解决方案