1.添加DataModel文件
2.添加实体和属性
@interface AppDelegate ()
@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic,strong) NSManagedObjectModel *managedObjectModel;
@property (nonatomic,strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@end
5.在AppDelegate.m文件的@implementation底部添加以下代码:
#pragma mark - Core Data
-(NSManagedObjectModel *)managedObjectModel
{
if(_managedObjectModel == nil)
{
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"DataModel" ofType:@"momd"];//这里的DataModel与第1步创建的文件名对应
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return _managedObjectModel;
}
-(NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
//NSLog(@"%@",documentsDirectory);
return documentsDirectory;
}
-(NSString *)dataStorePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:@"DataStore.sqlite"];
}
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if(_persistentStoreCoordinator == nil)
{
NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error;
if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(@"Error adding persistent store %@,%@",error,[error userInfo]);
abort();
}
}
return _persistentStoreCoordinator;
}
-(NSManagedObjectContext *)managedObjectContext
{
if(_managedObjectContext == nil)
{
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
if(coordinator != nil)
{
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return _managedObjectContext;
}
6.在需要应用Core Data进行数据操控的视图控制器的.h头文件中添加以下代码:
@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
7.在AppDelegate.m文件中分别#import以上视图控制器的.h文件,并将AppDelegate创建的managedObjectContext的指针传递给以上控制器
如:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
CurrentLocationViewController *currentLocationViewController = (CurrentLocationViewController *)tabBarController.viewControllers[0];
currentLocationViewController.managedObjectContext = self.managedObjectContext;//传递指针
UINavigationController *navigationController = (UINavigationController *)tabBarController.viewControllers[1];
LocationsViewController *locationsViewController = (LocationsViewController *)navigationController.viewControllers[0];
locationsViewController.managedObjectContext = self.managedObjectContext;//传递指针
MapViewController *mapViewController = (MapViewController *)tabBarController.viewControllers[2];
mapViewController.managedObjectContext = self.managedObjectContext;//传递指针
return YES;
}
当以上视图控制器切换到其他需要应用Core Data操控数据的视图控制器时,可通过prepareForSegue将managedObjectContext的指针传递过去
如:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"TagLocation"])
{
UINavigationController *navigationController = segue.destinationViewController;
LocationDetailsViewController *controller = (LocationDetailsViewController *)navigationController.topViewController;
controller.coordinate = _location.coordinate;
controller.placemark = _placemark;
controller.managedObjectContext = self.managedObjectContext;//传递指针
}
}
(1)添加数据:
Location *location = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:self.managedObjectContext];
//设置实体的属性
location.locationDescription = _descriptionText;
location.category = _categoryName;
location.latitude = @(self.coordinate.latitude);
location.longitude = @(self.coordinate.longitude);
location.date = _date;
location.placemark = self.placemark;
NSError *error;
if(![self.managedObjectContext save:&error])
{
//添加处理错误情况的代码
return;
}
(2)修改数据:
在获取数据【第(4)步】之后,对需要修改的实体的属性修改完之后,调用以下代码
NSError *error;
if(![self.managedObjectContext save:&error])
{
//添加处理错误情况的代码
return;
}
(3)删除数据:
[self.managedObjectContext deleteObject:location]; //传入需要删除的数据对象(实体)
NSError *error;
if(![self.managedObjectContext save:&error])
{
//添加处理错误情况的代码
return;
}
(4)获取数据:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// 设置要查询的实体
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity];
// 设置排序
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescriptor]];
// 执行请求
NSError *error;
NSArray *foundObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (foundObjects == nil) {
//添加处理错误情况的代码
return;
}
_locations = foundObjects; //将获取的数据赋值给实例变量