ios coreData 学习

来源:互联网 发布:在线监测数据造假刑法 编辑:程序博客网 时间:2024/06/05 20:19


1. 首先建一个Model.xcdatamodeld文件 如上图所示


2.在ViewController文件中 初始化 NSManagedObjectContext(在进入到CoreDataViewController之前必须首先初始化NSManagedObjectContext)


3. 在NSManagedObjectContext中实现增删改查和保存数据


ViewController头文件

@interface ViewController : BaseViewController{@private    NSManagedObjectContext *managedObjectContext_;    NSManagedObjectModel *managedObjectModel_;    NSPersistentStoreCoordinator *persistentStoreCoordinator_;}@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (NSURL *)applicationDocumentsDirectory;

ViewControllerm文件

 CoreDataViewController *_viewControll = [[CoreDataViewController alloc]init];    //实例化managedObjectContext并且传给控制器,此处必须在testcontroller显示前完成    _viewControll->managedObjectContext = [self managedObjectContext];    [self.navigationController pushViewController:_viewControll animated:YES];

/** applicationWillTerminate: saves changes in the application's managed object context before the application terminates. */- (void)saveCoreData{    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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.             */            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);            abort();        }    }}#pragma mark -#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_;    }    //模型的名称必须和Model.xcdatamodel的相同    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" 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:@"Entityest.data"];        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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.                  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:         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];                  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 -#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];}


CoreDataViewController h文件

#import <CoreData/CoreData.h> @interface CoreDataViewController : CHBaseViewController{    NSMutableArray *eventsArray;@public    NSManagedObjectContext *managedObjectContext;}- (NSURL *)applicationDocumentsDirectory;


CoreDataViewController m文件

#import "CoreDataViewController.h"#import "Entity.h"@implementation CoreDataViewController- (void)viewDidLoad{    [super viewDidLoad];        [self setTopNavBarTitle:@"CoreDataViewController"];        [self setTopNavBackButton];        self.view.backgroundColor = [UIColor whiteColor];}-(void)viewWillAppear:(BOOL)animated{        //添加数据    [self addFavorite];            //删除数据    //[self deleteFavorite];        //更新    //[self updateFavorite];        NSMutableArray *mutableFetchResults =[self readFavorites];            for (Entity * item in mutableFetchResults)    {        NSLog(@"%@,%@",item.body,item.title);    }        //NSLog(@"%@",mutableFetchResults);    //NSLog(@"%@",[[mutableFetchResults objectAtIndex:0] AppID]);    }-(NSMutableArray *)readFavorites{    //初始化一个“获取请求”到我们的实体“Favorite”    NSFetchRequest *request = [[NSFetchRequest alloc] init];    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:managedObjectContext];    [request setEntity:entity];        //排序   /* NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"AppID" ascending:YES];    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];    [request setSortDescriptors:sortDescriptors];*/        // 执行“获取”操作,得到一个“可变数组”的拷贝    NSError *error = nil;    NSMutableArray *mutableFetchResults = [[managedObjectContext                                            executeFetchRequest:request                                            error:&error] mutableCopy];    if (mutableFetchResults == nil)    {        //如果结果为空,在这作错误响应    }    return mutableFetchResults ;}- (void)addFavorite{    //建立一个Favorite实体对象    Entity *entity = (Entity *)[NSEntityDescription                                    insertNewObjectForEntityForName:@"Entity"                                    inManagedObjectContext:managedObjectContext];    //赋值   // [Entity setbody:[NSNumber numberWithInt:12101]];    //[Entity setBody:@"45655"];        [entity setBody:@"sww"];        [entity setTitle:@"fuck"];        // 保存更改,也可以最后一起保存到数据库,未保存到数据库前的数据都在内存中    NSError *error;    if (![managedObjectContext save:&error])    {        // Handle the error.    }}-(void)deleteFavorite{    NSMutableArray *mutableFetchResults =[self readFavorites];    [managedObjectContext deleteObject:[mutableFetchResults objectAtIndex:0]];    // 保存更改,如果没保存的话,只是内存中删除了,并没有真正的删除    NSError *error;    if (![managedObjectContext save:&error])    {        // Handle the error.    }}-(void)updateFavorite{    NSMutableArray *mutableFetchResults =[self readFavorites];    Entity * item = [mutableFetchResults objectAtIndex:0];    item.title = @"updateFavorite";    [managedObjectContext refreshObject:item mergeChanges:YES];    NSError *error;    if (![managedObjectContext save:&error])    {        // Handle the error.    }}



0 0
原创粉丝点击