您的位置:首页 > 移动开发 > IOS开发

iOS 数据持久化-CoreData

2015-09-14 16:17 656 查看
在新建勾选CoreData项目,当然也可以自己添加.

这里采用自己新建一个CoreDataUtil类,使用单例模式,以便后期使用:

CoreDataUtil.h文件:#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CoreDataUtil : NSObject

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

+(CoreDataUtil *) sharedManager;
@end

CoreDataUtil.m文件:

@implementation CoreDataUtil

+(CoreDataUtil *) sharedManager{
static CoreDataUtil *instance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate,^{
instance = [[CoreDataUtil alloc]init ];
});
return instance;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "longer.CoreDataTest" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataTest" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}

// Create the coordinator and store

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this 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 _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext 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();
}
}
}

@end


具体方法其实只要在新建项目时勾选了CoreData,在AppDelegate中会自动生成,参考着copy改就成.
------------------------------------------------------------------

下面是要在某个类中利用CoreData 实现增删改查:

首先声明属性

@property (nonatomic,strong) CoreDataUtil *coreDateUtil;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

再对自身的属性进行赋值,方便编程习惯
_coreDateUtil = [CoreDataUtil sharedManager];
self.managedObjectContext = _coreDateUtil.managedObjectContext;
self.managedObjectModel = _coreDateUtil.managedObjectModel;
self.persistentStoreCoordinator = _coreDateUtil.persistentStoreCoordinator;


之后就是增:
- (IBAction)insert:(id)sender {
//创建实体
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
if (newPerson != nil) {
newPerson.name = @"KILLER";
newPerson.age = [NSNumber numberWithInt:20];

// 保存数据
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(@"success");
}else{
NSLog(@"failed to save the context error = %@",savingError);
}
}else{
NSLog(@"failed to create the new Person");
}
}

删:
- (IBAction)delete:(id)sender {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSError *requestError = nil;
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
if ([persons count]>0) {
Person *lastPerson = [persons lastObject];
[self.managedObjectContext deleteObject:lastPerson];
if ([lastPerson isDeleted]) {
NSLog(@"successful deleted the lastPerson");
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(@"successful saved the context");
}else{
NSLog(@"failed to save the context error = %@",savingError);
}
}else{
NSLog(@"failed to deleted the lastPerson");
}
}else{
NSLog(@"could not find any person in the context");
}

}

改:
- (IBAction)update:(id)sender {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *requestError = nil;
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
if ([persons count] > 0) {
Person *lastPerson = [persons lastObject];
lastPerson.name = _name.text;
lastPerson.age = [NSNumber numberWithInt:[ _age.text intValue]];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(@"successfully saved the context");
}else{
NSLog(@"failed to save the context error = %@",savingError);
}
}else{
NSLog(@"could not find any person in the context");

4000
}
}

查:
- (IBAction)find:(id)sender {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *requestError = nil;
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
int count = 0;
for (Person *person in persons){
NSLog(@"person-->%d,name = %@,age = %d",count,person.name,[person.age intValue]);
count ++;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: