Core Data 的简单使用
认识cocoa Data在ios开发中的环境情况。
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" height="430" width="721">
Core Data简单使用的样例。可以使用模板中的master—detail 这种控制器组合可以轻松完毕。
主要的文件夹框架:
对应的Core Data中的基本对象都会自己主动生成。
masterController.md的代码:
//
// MasterViewController.m
// Tasks
//
// Created by 朱敏 on 15/8/24.
// Copyright (c) 2015年 helinyu. All rights reserved.
// #import "MasterViewController.h"
#import "DetailViewController.h"
#import "TaskEntryViewController.h" @interface MasterViewController () @end @implementation MasterViewController - (void)awakeFromNib {
[super awakeFromNib];
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)insertNewObject:(id)sender { TaskEntryViewController *tevc = [[TaskEntryViewController alloc]init];
tevc.managedObjectContext = self.managedObjectContext; [self presentViewController:tevc animated:YES completion:nil];
// NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
// NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
// NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
//
// // If appropriate, configure the new managed object.
// // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
// [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
//
// // Save the context.
// NSError *error = nil;
// if (![context 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();
// }
} #pragma mark - Segues - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
[[segue destinationViewController] setDetailItem:object];
}
} #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
return [sectionInfo numberOfObjects];
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];
return cell;
} - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
} - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; NSError *error = nil;
if (![context 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();
}
}
} - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [[object valueForKey:@"taskText"] description];
cell.detailTextLabel.text = [[object valueForKey:@"timeStamp"] description];
} #pragma mark - Fetched results controller - (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
} NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
// NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20]; // Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController; NSError *error = nil;
if (![self.fetchedResultsController performFetch:&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();
} return _fetchedResultsController;
} #pragma mark NSFetchedResultsControllerDelegate - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
} - (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; default:
return;
}
} - (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:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break; case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
break; case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break; case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
} - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
} /*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/ @end
detail中的代码没有什么改动,创建之后就能够生成,这个我们就无论了
TaskEntryViewController.m文件的代码:
//
// TaskEntryViewController.m
// Tasks
//
// Created by 朱敏 on 15/8/24.
// Copyright (c) 2015年 helinyu. All rights reserved.
// #import "TaskEntryViewController.h" @interface TaskEntryViewController () @end @implementation TaskEntryViewController - (void)viewDidLoad {
[super viewDidLoad]; // NSSet
self.tf = [[UITextField alloc]initWithFrame:CGRectMake(65, 20, 200, 20)];
[self.tf setBackgroundColor:[UIColor lightGrayColor]];
[self.tf setDelegate:self ];
[self.view addSubview:self.tf]; UILabel *lb1 = [[UILabel alloc]initWithFrame:CGRectMake(5, 20, 60, 20)];
[lb1 setText:@"Task"]; [self.view addSubview:lb1];
} - (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSManagedObjectContext *context = self.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:context];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
[newManagedObject setValue:[self.tf text] forKey:@"taskText"]; NSError *error = nil; if (![context save:&error]) {
NSLog(@"Unresolved error %@,%@",error,[error userInfo]);
abort();
} [self dismissViewControllerAnimated:YES completion:nil]; return YES;
} @end
对应的storyBoard的改变的界面:
上面执行就能够成功了。
Core Data 的简单使用的更多相关文章
- Core Data 学习简单整理01
Core Data是苹果针对Mac和iOS平台开发的一个框架, 通过CoreData可以在本地生成数据库sqlite,提供了ORM的功能,将对象和数据模型相互转换 . 通过Core Data管理和操作 ...
- Core Data的简单用法
#import "ViewController.h" // 第一步:引入头文件AppDelegate #import "AppDelegate.h" #impo ...
- iphone数据存储之-- Core Data的使用(一)
http://www.cnblogs.com/xiaodao/archive/2012/10/08/2715477.html 一.概念 1.Core Data 是数据持久化存储的最佳方式 2.数据最终 ...
- (转)iphone数据存储之-- Core Data的使用
原文:http://www.cnblogs.com/xiaodao/archive/2012/10/08/2715477.html iphone数据存储之-- Core Data的使用(一) 一. ...
- Core Data (2)-备用
1.Core Data 是数据持久化存储的最佳方式 2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型 在Mac OS X 10.5Leopard及以后的版本中 ...
- IOS 数据存储之 Core Data详解
Core Date是ios3.0后引入的数据持久化解决方案,它是是苹果官方推荐使用的,不需要借助第三方框架.Core Date实际上是对SQLite的封装,提供了更高级的持久化方式.在对数据库操作时, ...
- 数据存储-- Core Data的使用(一)
一.概念 1.Core Data 是数据持久化存储的最佳方式 2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型 在Mac OS X 10.5Leopard及以 ...
- iphone数据存储之-- Core Data的使用
一.概念 1.Core Data 是数据持久化存储的最佳方式 2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型 在Mac OS X 10.5Leopard及以 ...
- IOS 数据存储之 Core Data具体解释
Core Date是ios3.0后引入的数据持久化解决方式,它是是苹果官方推荐使用的.不须要借助第三方框架.Core Date实际上是对SQLite的封装.提供了更高级的持久化方式.在对数据库操作时, ...
随机推荐
- SQL——时间戳
mysql 低版本,date.datetime.timestamp 无法精确到毫秒 可以舍弃时间类型字段,用 bigint 来代替,如果用字符串类型代替,还是比较担心排序的时候只是根据第一个字母进行排 ...
- HTML标签的分类
html中的标签元素大体被分为三种不同的类型:块状元素.内联元素和内联块状元素.常用的块状元素有:<div>.<p>.<h1>...<h6>.<o ...
- CAD参数绘制直径标注(网页版)
主要用到函数说明: _DMxDrawX::DrawDimDiametric 绘制一个直径标注.详细说明如下: 参数 说明 DOUBLE dChordPointX 在被标注的曲线上的第一个点X值 DOU ...
- JavaSE-15 Log4j参数详解
一:日志记录器输出级别,共有5级(从前往后的顺序排列) ①fatel:指出严重的错误事件将会导致应用程序的退出 ②error:指出虽然发生错误事件,但仍然不影响系统的继续运行 ③warn:表明会出现潜 ...
- JAVA基础——设计模式之单列模式
一:单例设计模式 Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点. 单例设计模式的特点: 单例类只能 ...
- 如何手写一款KOA的中间件来实现断点续传
本文实现的断点续传只是我对断点续传的一个理解.其中有很多不完善的地方,仅仅是记录了一个我对断点续传一个实现过程.大家应该也会发现我用的都是一些H5的api,老得浏览器不会支持,以及我并未将跨域考虑入内 ...
- javaScript中计算字符串MD5
进行HTTP网络通信的时候,调用API向服务器请求数据,有时为了防止API调用过程中被黑客恶意篡改,所请求参数需要进行MD5算法计算,得到摘要签名.服务端会根据请求参数,对签名进行验证,签名不合法的请 ...
- CF508E Arthur and Brackets
题目大意:给出n对括号,并给出每对括号距离的范围.问能否找到这样一个序列. 题解:好多人都用贪心.这么好的题为什么不搜一发呢? 注意:千万不要在dfs里面更新答案. 代码: #include<c ...
- Python 文件修改-函数介绍
上节课复习:1.字符编码 1.1 如何解决乱码问题: 字符存取使用的编码标准不一致 1.2 文件头 在文件的首行写入文件头,用于控制Python解释器读取py文件内容时使用的编码 #coding:文件 ...
- MySQL-----一对一
一对一: 用户表和博客表 用户表(userinfo): 用户id 用户名 1 George 2 root 3 Bruce 4 Catherine 博客表: 博客id 博客名 用户id(FK + 唯一) ...