最近有小伙伴问我coreData的使用,而且上次写了一篇关于地图定位文章帮到了有需要的人,我感到很高兴, 所以我想分享一下Xcode 自带的CoreData的使用。
Apple自带的coreData真的很强大,它基于Sqlite进行数据的存储和删除等操作,不需要引入像FMDB等这类第三方,基本上能够满足项目的需求。但是FMDB也是一个很不错的第三方,如果后台给你的数据全都存在db库里面,现在使用FMDB就显得格外的轻松。
好了,直接进入主题,谁让我就喜欢直来直去。
Step1:
创建工程的时候选中 Use CoreData
Step2:
建表
在工程中选中 coreData表 —》点击 Add Entity —》然后双击修改 Entity的名称(这里在将来存储数据的时候就靠这个名称来查找,相当于Sqlite中的 表名称)—》 点击 Attributes 下的 + 号,添加对应存储的内容的key值(相当于Sqlite中的条件字段)
效果如下:
Step3:
导出对应的类
1、在Editor中选中 Create NSManagedObject Subclass…
2、选中项目 点击Next
3、选中需要导出的表 点击Next
4、找好存储路径 点击 create
Step4:
导入头文件, 我是在 pch文件中导入的,方便项目中的使用, 也可以在哪个类中使用,直接导入即可
Step5:
是时候展现真正的技术了(坏笑)
1、存储数据
- (void)saveDataWithName:(NSString *)name andIndex:(NSInteger)index
{
YingyongList *yingYongModel = [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:self.mangeContext];
//添加数据
yingYongModel.btn_image = self.imageViewArray[index];
yingYongModel.title = self.titleArray[index];
//每次操作完一定要记住保存,否则数据操作失败
[self.mangeContext save:nil];
}
2、删除数据
- (void)deleteDataFromCoreDataWith:(NSString *)name
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:name inManagedObjectContext:self.mangeContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [self.mangeContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
}
else{
for (int i = 0; i < fetchedObjects.count; i++) {
[self.mangeContext deleteObject:fetchedObjects[i]];
}
[self.mangeContext save:nil];
}
}
3、插入数据
- (void)insertDataWithName:(NSString *)name
{
YingyongList *yingYongModel = [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:self.mangeContext];
yingYongModel.btn_image = self.imageViewArray[index];
yingYongModel.title = self.titleArray[index];
}
4、获取存储的数据
//从本地化取数据
- (NSArray *)getTheDataFromDocumentWithName:(NSString *)name
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:name inManagedObjectContext:self.mangeContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [self.mangeContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
return nil;
}
else{
return fetchedObjects;
}
}
注意: 如果项目新版对CoreData中的表进行了修改,这个时候时候导致崩溃的,有两种解决办法:
1、删除项目重新下载,这个估计你的老板不会同意
2、在 Appdelegate 的 -(NSPersistentStoreCoordinator *)persistentStoreCoordinator 方法里面添 加下面的参数:
//++++++++++参数++++++++++++++++
//NSSQLiteStoreType 文件类型
//storeURL 存储路径
//options 支持版本自动更新参数
/*NSInferMappingModelAutomaticallyOption :@YES
NSMigratePersistentStoresAutomaticallyOption : @YES
*/
NSDictionary *options = @{NSInferMappingModelAutomaticallyOption : @YES, NSMigratePersistentStoresAutomaticallyOption : @YES};
//参数的使用
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options 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();
}
CoreData的强大远不止上面这些,这只是我的一些简单使用,他还可以在表之间建立一种 clasship,关联不同的表。 在项目中如果使用CoreData进行数据管理,也可以对其进行封装,方便项目的使用。
如有问题,欢迎交流学习
Email: 18729030047@163.com