首先使用CoreData创建Demo,勾上CoreData选项
然后创建Entity对象,点击Add Entity(+)按钮
生成Entity对象
重命名双击Entity选项,然后输入Person
设置Person属性,点击Attributes选项中的+号,实现添加属性,并给属性命名,且添加属性相关的类型
然后command+N,创建NSManagedObject subclass
然后点击Next
然后勾上 CoreData_Demo选项,然再点击Next
接着勾上Person选项,再次点击Next
接下来,跟着系统的提示进行操作,最后生成Person类
下面是相关操作的代码
AppDelegate.h头文件的代码
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext;
- (NSURL *)applicationDocumentsDirectory; @end
AppDelegate.h实现文件的代码
#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible];
return YES;
} - (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
} #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 "com.YXYC.Test_CoreData_Test" 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:@"Test_CoreData_Test" 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:@"Test_CoreData_Test.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: 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
RootViewController.h头文件相关的代码
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
RootViewController.h实现文件相关的代码
#import "RootViewController.h"
#import "AppDelegate.h"
@interface RootViewController () @property (strong, nonatomic) AppDelegate *appDelegate; @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad];
self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// 存储数据
[self saveData];
// 查询全部数据
[self readData];
NSMutableArray *datas = [[NSMutableArray alloc] init];
// 得到查询的结果(条件查询)
datas = [self getObjectsWithPredicate];
// 删除
[self removeObjects];
// 修改
[self changeObjects];
} /**
* 存储数据
*/
- (void)saveData
{
NSManagedObjectContext *object = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
[object setValue:@"GL" forKey:@"name"];
[object setValue:@"female" forKey:@"sex"]; } /**
* 查询全部数据
*/
- (void)readData
{
// 实例化一个查询(Fetch)请求
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *object = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
[fetch setEntity:object]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSLog(@"sort:%@",sort); NSArray *sortarr = [[NSArray alloc] initWithObjects:sort, nil];
[fetch setSortDescriptors:sortarr]; NSError *error = nil;
// 让_context执行查询数据
NSArray *fetchresult = [self.appDelegate.managedObjectContext executeFetchRequest:fetch error:&error]; for (NSManagedObject *object in fetchresult) {
NSLog(@"name:%@==sex:%@",[object valueForKey:@"name"],[object valueForKey:@"sex"]);
} }
/**
* 条件查询
*
* @return 查询结果的Entity数组
*/
- (NSMutableArray *)getObjectsWithPredicate
{
NSError *error = nil;
// 实例化一个查询(Fetch)请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 条件查询
request.predicate = [NSPredicate predicateWithFormat:@"sex LIKE '*female'"];
// 让_context执行查询数据
NSArray *array = [self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
return [NSMutableArray arrayWithArray:array];
}
/**
* 删除操作
*/
- (void)removeObjects
{
NSError *error = nil;
// 实例化查询请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 设置条件
request.predicate = [NSPredicate predicateWithFormat:@"name = 'LF'"];
// 由上下文查询数据
NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
// 打印条件结果,并删除对象
for (NSManagedObject *object in result) {
// 删除对象
[self.appDelegate.managedObjectContext deleteObject:object];
}
// 删除后,保存数据
[self.appDelegate.managedObjectContext save:&error];
}
/**
* 修改
*/
- (void)changeObjects
{
NSError *error = nil;
// 实例化查询请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 设置条件
request.predicate = [NSPredicate predicateWithFormat:@"name = 'GL'"];
// 由上下文查询数据
NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
// 修改对象
for (NSManagedObject *object in result) {
// 修改对象
[object setValue:@"GYL" forKey:@"name"];
}
// 修改后,保存数据
[self.appDelegate.managedObjectContext save:&error];
} @end