码迷,mamicode.com
首页 > 其他好文 > 详细

CoreData-基本语法.

时间:2015-04-21 22:22:06      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

1. 在使用StoryBoard时通过 UIApplicationDelegate 来获得AppDelegate 从而获得内容上下文

    AppDelegate * delegateVC = [UIApplication sharedApplication].delegate;

    self.context = delegateVC.managedObjectContext;

2. 数据查询.

  设置一个请求用来进行查询

  NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

  设置一个描述实体类.

  NSEntityDescription * description = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.context];

 将实体添加到请求中

  [fetchRequest setEntity:description];

  开始请求 返回的是数据库中的相关的数组.

  NSArray * array = [self.context executeFetchRequest:fetchRequest error:nil];

3. 添加数据

  得到一个描述实体类   可以理解为向表Student中添加一条记录. 此时的student并没有具体的值.

  Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];

  给student赋值.根据自己定义的数据结构

  student.name = @"111";      student.phoneNumber = @"222";       student.sex = @"f";

  保存数据.

  [self.context save:nil];

4. 删除数据.

   得到要删除的数据对象.

    NSManagedObject * object = _dataArray[indexPath.row];

   删除数据库中的对象.

    [self.context deleteObject:object];

   更新数据库

    [self.context save:nil];

5  进行版本升级.

   在AppDelegate的 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator 的方法中填上允许版本升级的代码.

  支持版本迁移, 默认为nil

    NSDictionary * dic = @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES};

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:dic error:&error])

6 在数据查询中直接进行排序.

   获得请求并关联实体

    NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];

   设置排序字段.

    NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

  将排序添加到请求中.

    [request setSortDescriptors:@[sort]];

    coreData查询操作,返回的是一个数组.

    NSArray * dataArray = [self.context executeFetchRequest:request error:nil];

7 让最后添加的数据最先显示.

   设置数据在TableView中插入的位置.

    NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:0];

    设置插入的位置,以及插入的动画.

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:index, nil] withRowAnimation:UITableViewRowAnimationRight];

    //设置滚动效果

    [self.tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];

 

CoreData-基本语法.

标签:

原文地址:http://www.cnblogs.com/jfhn/p/4445442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!