一. 你可以在创建项目的时候勾选CoreData的勾勾,这样创建出来的项目在AppDelegate.h和m文件中会自动生成CoreData的一些方法,以及回自动生成.xcdatamodeld文件
二.或者自己创建.xcdatamodeld文件,倒入CoreData.framework文件,自定义创建一个继承与NSObject的类讲CoreData一些必备方法写入,调用.h/m文件如下
1.创建数据模型
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CoreDateTwo : NSObject
@property (nonatomic, strong) NSString *coreDataName;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
//单例使用
+(instancetype)share;
- (void)createTest;
@end
#import "CoreDateTwo.h"
#import "Failedone.h"
#import "FailedTwo.h"
@implementation CoreDateTwo
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (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:@"TestCoreDate2" withExtension:@"momd"];
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:_coreDataName withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"TestCoreDate2.sqlite"];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",_coreDataName]];
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]) {
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];
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] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
+(instancetype)share{
static CoreDateTwo *shareObject;
static dispatch_once_t one;
dispatch_once(&one,^{
shareObject = [[CoreDateTwo alloc] init];
});
return shareObject;
}
-(void)createTest{
NSManagedObjectContext *context = [self managedObjectContext];
Failedone *failedBankInfo = [NSEntityDescription insertNewObjectForEntityForName:@"Failedone"inManagedObjectContext:context];
failedBankInfo.title = @"Testville";
failedBankInfo.number = [NSNumber numberWithInt:16];
FailedTwo *failedBankDetails = [NSEntityDescription insertNewObjectForEntityForName:@"FailedTwo"inManagedObjectContext:context];
failedBankDetails.title = @"failedBankDetail";
failedBankDetails.one = failedBankInfo;
failedBankInfo.two = failedBankDetails;
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// Test listing all FailedBankInfos from the store
//这里我们创建一个叫做fetch request的新方法,你可以将一个fetch request看做Sql中的select语句,我们调用entityForName方法来获取一个指向FailedBankInfo的指针,之后使用setEntity方法来告诉我们的fetch request我们想要的是哪一种的实体。
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Failedone"inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (Failedone *info in fetchedObjects) {
NSLog(@"Name: %@", info.title);
FailedTwo *details = info.two;
NSLog(@"Zip: %@", details.title);
}
}
@end