今天学习了 ios 中 使用Core Data进行持久化,首先说一下对这东西的理解
Core Data是一种 稳定,功能全面的持久化工具,和之前的一些持久化 工具相比,他不需要对实体进行归档,也就是序列化,而是在数据 模型编辑器中创建一些实体
在代码中,你不再使用存取方法和修改方法,而是使用键值对编码来设置属性或者减缩他们的值
那么这些托管对象的活动区域在哪 ? 他们位于所谓的持久库中,默认情况下,Core Data应用程序将持久库实现为存储在应用程序文档目录的sqlite数据库。
虽然数据是通过sqlite存储的,但框架中的类将完成加载和保存数据的相关工作。不许要编写任何sql语句。下面贴代码。
首先我创建了一个名字叫Line的实体,其中含两个属性 很简单,(int) lineNum和 (string)lineText
/////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext]; //创建上下文
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];//创建实体
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!");
}
//循环得到的对象数组
for (NSManagedObject *oneObject in objects) {
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
NSString *lineText = [oneObject valueForKey:@"lineText"];
NSString *fieldName = [NSString stringWithFormat:@"field%d",lineNum];
UITextField *theField = [self valueForKey:fieldName];
theField.text = lineText;
}
[request release];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[super viewDidLoad];
}
/////////////////////////////////////////////////////////////////////
Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
for (int i = 1; i<=4; i++) {
NSString *fieldName = [NSString stringWithFormat:@"field%d",i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
[request setEntity:entityDescription];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)",i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(@"There was an error!");
}
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"];
[request release];
}
[context save:&error]; //最后保存实体 如果保存出错会返回error
初级应用 希望对初学者 有帮助