CoreData的使用

转载 2012年03月30日 13:21:09

第一步:创建一个 DataDemo.xcdatamodel 文件,在其中建一个实体名字为 Entity1 ,实体中建两个字段 id 和 name。

第二步:为项目添加 CoreData.framework 框架,然后在 .pch 中加入 #import <coredata/coredata.h>

第三步:在 app delegate 中定义 core data 的相关对象(同时完成它们的初始化工作)

.h 文件:

#import <coredata/coredata.h>

@private   
    NSManagedObjectModel *managedObjectModel;
    NSManagedObjectContext *managedObjectContext;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;

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

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

.m 文件:

@synthesize managedObjectModel;
@synthesize managedObjectContext;
@synthesize persistentStoreCoordinator;

- (void)dealloc {
    [managedObjectModel release];
    [managedObjectContext release];
    [persistentStoreCoordinator release];
    [super dealloc];
}

- (NSString*)applicationDocumentsDirectory

    //return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
    //return [NSURL URLWithString:basePath];
}

- (void)saveContext{    
   NSError *error = nil;   
   NSManagedObjectContext *objectContext = self.managedObjectContext;   
   if (objectContext != nil)   
   {       
 if ([objectContext hasChanges] && ![objectContext save:&error])     
 {
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);       
  abort();     
 }   
   }
}

- (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;
    }
    //从本地所有 xcdatamodel 文件中获得这个 CoreData 的数据模板
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    //数据库名为TestDB.sqlite
    NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"TestDB.sqlite"]];
    NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        NSAssert(0, @"persistentStoreCoordinator init failed!");
    }
    return persistentStoreCoordinator;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSError *error;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSAssert(0, @"save changes failed when terminage application!");
        }
    }
}

第四步:在相关的 viewcontroller 中操作数据,基本的 core data 操作代码如下:

 NSError *error;
 testSQLiteAppDelegate *app = (testSQLiteAppDelegate*)[[UIApplication sharedApplication] delegate];
 NSManagedObjectContext *context = app.managedObjectContext;
 
 //1、插入
 NSManagedObject *newManagedObject  = nil;
 newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Entity1" inManagedObjectContext:context];
 [newManagedObject setValue:[NSNumber numberWithInt:1] forKey:@"id"];
 [newManagedObject setValue:@"i love you" forKey:@"name"];
 if (![context save:&error]){
    NSLog (@"The error is: %@", [error userInfo]);
 }
 else
 {
    NSLog (@"The newManagedObject's id is: %@", [newManagedObject valueForKey:@"id"]);
 }

 //2、查询
 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity1" inManagedObjectContext:context];
 NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
 NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
 NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
 [fetchRequest setSortDescriptors:sortDescriptors];
 [fetchRequest setEntity:entity];
 [fetchRequest setFetchBatchSize:20];
 NSArray *objects = [context executeFetchRequest: fetchRequest error:&error];
 if (objects == nil)
 {
     NSLog(@"There was an error!");
 }
 else {
    for (NSManagedObject *oneObject in objects)
    {
       NSLog(@"%@",[oneObject valueForKey:@"name"]);
    }        
 }

 //3、删除
 [context deleteObject:[objects objectAtIndex:0]];
 if (![context save:&error]) {
      exit(-1);
 }

这里更详细的补充一点关于 core data 的操作代码:

1、条件过滤:选择 cid=1 的数据

 - (NSFetchedResultsController*) fetchedResultsController
 {    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid=1"];    
    [fetchRequest setPredicate:predicate];
 }

2、通用代码,在 viewcontroller 里面会用到:

TestViewController.h 的代码:

@interface TestViewController : UITableViewController <NSFetchedResultsControllerDelegate>
{    
    NSFetchedResultsController *fetchedResultsController;
    NSManagedObjectContext *managedObjectContext;      
}  

@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;  

- (void)configureCell:(UITableViewCell *)cell withCategory:(Category *)category;

@end

TestViewController.m 的代码:

 -(NSFetchedResultsController *)fetchedResultsController
 {    
     if (fetchedResultsController != nil)
     {    
          return fetchedResultsController;
     }    
     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];    
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:managedObjectContext];  
     [fetchRequest setEntity:entity];         
     NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];    
     NSArray *arraySortDescriptor = [[NSArray alloc] initWithObjects:nameDescriptor, nil];   
     [fetchRequest setSortDescriptors:arraySortDescriptor];          
     NSPredicate *predicate = [NSPredicate predicateWithFormat:cidString];    
     [fetchRequest setPredicate:predicate];          
     NSFetchedResultsController *frController =  [[NSFetchedResultsController alloc]
     initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"name" cacheName:@"Root"];    
     frController.delegate = self;
     self.fetchedResultsController = frController;          
     [frController release];    
     [fetchRequest release];    
     [nameDescriptor release];          
     return fetchedResultsController;
 }
 
 - (void)controllerWillChangeContent:(NSFetchedResultsController *)
 {    
    [self.tableView beginUpdates]; 
 }  
 
 - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType: (NSFetchedResultsChangeType)type
   newIndexPath:(NSIndexPath *)newIndexPath
   {    
      UITableView *tableView = self.tableView;    
      switch (type) {        
          case NSFetchedResultsChangeInsert:       
               [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];            
                break;                      
          case NSFetchedResultsChangeDelete:            
               [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];            
               break;                      
          case NSFetchedResultsChangeMove:            
              [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];                           

             [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];            
               break;                  
          case NSFetchedResultsChangeUpdate:            
               [self configureCell:[tableView cellForRowAtIndexPath:indexPath] withCategory:anObject];         
               break;                      
          default:            
               break;    
       }
   }
  
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
   {          
       switch(type) {                      
             case NSFetchedResultsChangeInsert:            
                 [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];                   

            break;                      
             case NSFetchedResultsChangeDelete:            
                 [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];                   

            break;    
        }
    }  
   
   - (void) controllerDidChangeContent:(NSFetchedResultsController *)controller
   {    
        [self.tableView endUpdates];
   }

相关文章推荐

coreData使用入门。

  • 2013-05-03 10:00
  • 81KB
  • 下载

IOS CoreData 使用(二)

实例背景描述:      在MKMapView视图上绘制多边形和圆形两种区域。首先从服务器上下载多个区域的JSon数据坐标,解析后存储到Core Data中。 一 ...

使用多个Context的CoreData

  • 2015-06-01 13:46
  • 560KB
  • 下载

CoreData的使用

  • 2016-08-10 22:59
  • 49KB
  • 下载

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

用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的。 首先: 1、网易新闻用CoreD...

coreData使用

  • 2016-03-26 10:02
  • 2.87MB
  • 下载

要用 CoreData 结合 UITableView 使用

最近几天学了 coreData 结合 UITableView 使用,自动更新内容. 下面是最简单的内容 创建 coreData : 新建—> Core Data-> Data Model  创建...

IOS coredata使用

  • 2014-01-22 16:59
  • 153KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)