前三篇我们学习了三种数据保存的方法.现在介绍一种最常用也是比较简单的方法
--coreData方法.
说到 CoreData方法,我们在建立项目的时候,必须选中 use coreData 复选框.然后建立 empty app的框架.
进入项目文件夹之后,我们就会发现一个 名叫 Core_Data__.xcdatamodeld 的文件.
点进去我们便可以对我们的模型进行添加实体并添加属性等操作.
我们用截图显示吧,你会看得更加清楚些.
2.然后看文件,由于我们建立的是一个空文件,所以我们需要添加我们自己的viewController.然后在代理中设置作为根目录视图(第三步).
先看看 BIDViewController.h文件,老样子,还是四个 textfield .
不过一定要设置成weak类型的哦,要不然又该出错了(上一篇已介绍).
#import <UIKit/UIKit.h>
@interface BIDViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *line1;
@property (weak, nonatomic) IBOutlet UITextField *line2;
@property (weak, nonatomic) IBOutlet UITextField *line3;
@property (weak, nonatomic) IBOutlet UITextField *line4;
@end
为了更加清晰的介绍,我把一些解释说明都写在代码注释中.
.m文件
#import "BIDViewController.h"
#import "BIDAppDelegate.h"
@interface BIDViewController ()
@end
@implementation BIDViewController
@synthesize line1,line2,line3,line4;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
BIDAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
//获得我们本项目的代理 用于 获得我们的管理对象上下文.
/*
下面的代码 在 delegate都是自动生成好的.我们只需要使用就可以啦.去查阅代理文件吧
#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;
}
*/
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription =[NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
//上一个方法是获得了我们的对象描述,简单的说,就是使用托管对象上下文描述一个名称为@"Line"的实体,但是还没有真实存在
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
//上一步是创建一个请求并把描述传递之,以便请求对象知道索要检索的对象名称.
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
//获得实体!!!!
if (objects == nil) {
NSLog(@"there was an error.");
}
//对获得的实体进行分割获得单个属性的value.
for (NSManagedObject *oneObject in objects) {
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];//获得 属性名位lineNum所存储的值
NSString *lineText = [oneObject valueForKey:@"linText"];//同上
//获得我们视图中出现的field的名称.
NSString *fieldName = [NSString stringWithFormat:@"line%d",[lineNum integerValue]];
//填充!
UITextField *thefield =[self valueForKey:fieldName];
thefield.text = lineText;
}
//发布广播消息.等待接受.也就是在本app后台运行的时候执行applicationWillResignActive方法.
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
// Do any additional setup after loading the view from its nib.
}
//简单的说,这个方法就是对我们在视图上的操作进行存储.
-(void)applicationWillResignActive:(NSNotification *)notification
{
BIDAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//获得托管对象上下文
NSError *error;
for (int i = 1; i < 4; i++) {
NSString *fieldName = [NSString stringWithFormat:@"line%d",i];//获得所要存储对象的名称
UITextField *thefield = [self valueForKey:fieldName];
//指向该textfield
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entitfDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
[request setEntity:entitfDescription];
//创建请求并发送描述
//建立谓词判断
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)",i];
[request setPredicate:pred];
NSArray *objects = [context executeFetchRequest:request error:&error];
//
if (objects == nil) {
NSLog(@"there 2 has an Error");
}
NSManagedObject *theLine = nil;
//查看返回的对象时候正确,要不就重新建立
if ([objects count] > 0) {
theLine = [objects objectAtIndex:0];
}
else
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line" inManagedObjectContext:context];
//添加
[theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
[theLine setValue:thefield.text forKey:@"lineText"];
}
[context save:&error];
//保存更改
}