如何使用Core Data
1个回答
展开全部
第一步:创建一个 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:nilURL: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.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:nilURL: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];
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询