有些同事觉得CoreData是一个看不懂,理解不清的神秘东东,其实ios的本地数据储存是一个sqlite数据库,一个简易的数据库,而这个CoreData是否支持所有储存的数据呢,显然不是的,站在我的角度,我是不支持把一些图片数据保存的CoreData里面,其一,如果保存图片需要把图片转化为Data类型,
UIImage * image = info[UIImagePickerControllerEditedImage];
//把Image转化成Data
self.imageData = UIImagePNGRepresentation(image);
其二,不具有稳定性。下面给大家讲解下CoreData的用法。
1.如果大家现在用Storyboard的,可以在建项目时选择在Use Core Data处打勾。
如果你是用纯代码写程序的话,那么你需要手动在AppDelegate里面写上这些代码
.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
.m
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != 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();
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn‘t already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn‘t already exist, it is created from the application‘s model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"App_7_addressbook" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn‘t already exist, it is created and the application‘s store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"App_7_addressbook.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application‘s Documents directory
// Returns the URL to the application‘s Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
这些就是需要建立cordata的根本,不需要你的理解。接下来我们就应该建立一个实体,对cordata不熟悉的技术人员也许疑问为什么简历实体?其实我们储存和获取数据没有对cordata直接操作,而是对实体进行操作。
创建一个model,这就是实体的,然后我们再创建一个实体类:
创建意识实体对象,然后生成一个实体类:
下面我们就对实体进行操作:
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
通过managedObjectContext进行储存操作,
首先对managedObjectContext进行初始化;
UIApplication * app = [UIApplication sharedApplication];
id delegate = [app delegate];
self.managedObjectContext = [delegate managedObjectContext];
1.然后在保存地方进行往coredata储存,
如:
self.p.number = self.numberT.text;
self.p.image = self.imageData;
NSError * error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"新建保存错误:%@",[error localizedDescription]);
}
进行保存。
2.在你从coredata获取数据的Controller写,
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property(nonatomic,strong)NSFetchedResultsController * fetchedResultsController;
这里的fetchedResultsController是从coredata获取数据,
- (void)viewDidLoad {
[super viewDidLoad];
UIApplication *application = [UIApplication sharedApplication];
id delegate = application.delegate;
self.managedObjectContext = [delegate managedObjectContext];
/*********
通过CoreData获取sqlite中的数据
*********/
//通过实体名获取请求
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Time class])];
//定义分组和排序规则
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timego" ascending:NO];
//把排序和分组规则添加到请求中
[request setSortDescriptors:@[sortDescriptor]];
//把请求的结果转换成适合tableView显示的数据
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
//执行fetchedResultsController
NSError *error;
if ([self.fetchedResultsController performFetch:&error]) {
NSLog(@"%@", [error localizedDescription]);
}
self.fetchedResultsController.delegate = self;
}
这些就是coredata基本简单用法,代码没有过多写,重要核心就是这些了