iOS使用CoreData实现收藏功能

实现收藏有很多方式,我在自己练习的项目中用CoreData实现了一下收藏功能,注释很少,算是自己做的一个笔记。
首先创建一个工具类继承NSObject,在里面实现所需要的方法.

工具类的.h文件:

<pre>
typedef NS_ENUM(NSUInteger, SelectInEntities) {

InEntities,
NotInEntities,
SelectError,

};

typedef NS_ENUM(NSUInteger, Entities) {

   NewsEntity,
   PostEntity,
  TypeEntity,
  ForumEntity,

};

@interface BFFCoreDataManager : NSObject

// 管理对象上下文(管理者)
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
// 管理对象模型(表结构)
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
// 持久化存储协调器(助理)
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// 保存上下文(保存对数据的修改)

  • (void)saveContext;
    // 沙盒路径
  • (NSURL *)applicationDocumentsDirectory;

//-(SelectInEntities)isInEntities:(Entities)entities
// Model:(id)model;

+(BFFCoreDataManager *)shareBFFCoreDataManager;

  • (id)isInEntities:(Entities)entities model:(id)model;
  • (BOOL)has:(NSMutableDictionary *)dic arr:(NSArray *)array;
    ///地方分会
  • (BOOL)hass:(NSMutableDictionary *)dic arr:(NSArray *)array;
    ///推荐论坛
  • (BOOL)hasss:(BFFDiscussModel *)model arr:(NSArray *)array;
  • (BOOL)haspost:(BFFSelectModel *)model arr:(NSArray *)array;
  • (BOOL)state:(NSArray *)arr url:(NSString *)url;
  • (BOOL)states:(NSArray *)arr ids:(NSString *)ids;
  • (id)myModel:(id)model;
    @property (nonatomic, strong) BFFCoreDataManager *manager;
    @end</pre>
工具类的.m文件

<pre>
@implementation BFFCoreDataManager
#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

  • (BFFCoreDataManager *)shareBFFCoreDataManager
    {
    /// 单例不能释放
    static BFFCoreDataManager *manager = nil;
    // 保证线程安全, 该方法只走一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    manager = [BFFCoreDataManager new];
    });
    return manager;
    }
    // 获取到沙盒的Document路径
  • (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.TheWorldCar" 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:@"TheWorldCar" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
    }

  • (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns 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:@"TheWorldCar.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    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();
    }

    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;
    }

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();
    }
    }
    }

  • (id)myModel:(id)model{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Type" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
    NSLog(@"%@", error);
    }
    BFFCollectModel *newsModel = model;
    for (Type *type in fetchedObjects) {
    if ([type.name isEqualToString:newsModel.name]) {
    return type;
    } else {
    return nil;
    }
    }

    return nil;
    }

// 判断是否在数据库中

  • (id)isInEntities:(Entities)entities model:(id)model
    {
    switch (entities) {
    case NewsEntity:
    {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
    NSLog(@"%@", error);
    }
    BFFNewsModel *newsModel = model;
    for (News *news in fetchedObjects) {
    if ([news.newsLink isEqualToString:newsModel.newsLink]) {
    return news;
    }
    }
    return nil;
    }
    break;
    case PostEntity:
    {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
    NSLog(@"%@", error);
    }
    BFFHotModel *hot = model;
    for (Post *post in fetchedObjects) {
    if ([post.postLink isEqualToString:hot.postLink]) {
    return post;
    }
    }
    return nil;
    }
    break;
    case TypeEntity:
    {

      }
          break;
      case ForumEntity:
      {
          NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
          NSEntityDescription *entity = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:self.managedObjectContext];
          [fetchRequest setEntity:entity];
          NSError *error = nil;
          NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
          if (fetchedObjects == nil) {
              NSLog(@"%@", error);
          }
          BFFCarDetailModel *carDetail = model;
          for (Line *line in fetchedObjects) {
              if ([line.seriesId isEqualToString:[NSString stringWithFormat:@"%@", carDetail.seriesId]]) {
                  return line;
              }
          }
          return nil;
      }
    
          break;
      default:
          break;
    

    }
    return nil;
    }

//爱车俱乐部.人车生活

  • (BOOL)has:(NSMutableDictionary *)dic arr:(NSArray *)array{
    NSNumber *num = dic[@"forumId"];
    for (Forum *forum in array) {
    if ([forum.postId isEqualToString:num.description]) {
    return YES;
    }
    }
    return NO;
    }

///地方分会

  • (BOOL)hass:(NSMutableDictionary *)dic arr:(NSArray *)array{
    NSNumber *num = dic[@"id"];
    for (Forum *forum in array) {
    if ([forum.postId isEqualToString:num.description]) {
    return YES;
    }
    }
    return NO;
    }

///论坛推荐

  • (BOOL)hasss:(BFFDiscussModel *)model arr:(NSArray *)array{
    for (Forum *forum in array) {
    if ([forum.postId isEqualToString:model.forumId.description]) {
    return YES;
    }
    }
    return NO;
    }

///帖子收藏

  • (BOOL)haspost:(BFFSelectModel *)model arr:(NSArray *)array{
    for (Post *post in array) {
    if ([post.postLink isEqualToString:model.postLink]) {
    return YES;
    }
    }
    return NO;
    }

///改变帖子收藏按钮图标

  • (BOOL)state:(NSArray *)arr url:(NSString *)url{
    for (Post *post in arr) {
    if ([post.postLink isEqualToString:url]) {
    return YES;
    }
    }
    return NO;
    }

///改变论坛收藏按钮图标

  • (BOOL)states:(NSArray *)arr ids:(NSString *)ids{
    for (Forum *forum in arr) {
    if ([forum.postId.description isEqualToString:ids]) {
    return YES;
    }
    }
    return NO;
    }

/**-(SelectInEntities)isInEntities:(Entities)entities
Model:(id)model
{
switch (entities) {
case NewsEntity:
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(@"%@", error);
}
BFFNewsModel *newsModel = model;

        for (News *news in fetchedObjects) {

            if ([news.newsLink isEqualToString:newsModel.newsLink]) {
                return InEntities;
            } else {
                return NotInEntities;
            }

        }

    }
        break;
        case PostEntity:
    {

   }
        break;
        case LineEntity:
    {

   }
        break;
        case ForumEntity:
    {

    }
       break;
   default:
        break;
}
return SelectError;

}
@end

*/
</pre>

接下来在收藏页面创建一个Button实现收藏

<pre>

  • (void)collectionBut:(id)sender{

    BFFCollectModel *model = self.tempModel;
    if ([self.manager myModel:model] == nil) {
    Type *type = [NSEntityDescription insertNewObjectForEntityForName:@"Type" inManagedObjectContext:self.manager.managedObjectContext];
    type.name = model.name;
    type.priceRange = model.priceRange;
    type.photo = model.photo;
    type.uid = [NSString stringWithFormat:@"%@", model.uid];
    [self.manager saveContext];

      self.collectLabel.text = @"已经收藏";
      self.collectLabel.hidden = NO;
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          self.collectLabel.hidden = YES;
      });
    

    } else {
    [self.manager.managedObjectContext deleteObject:[self.manager myModel:model]];
    [self.manager saveContext];
    self.collectLabel.text = @"已取消收藏";
    self.collectLabel.hidden = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    self.collectLabel.hidden = YES;
    });
    }
    }

///在我的收藏页面把数据取出

  • (void)createLineData
    {
    self.typeArr = [NSMutableArray array];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Type" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    if (fetchedObjects == nil) {
    NSLog(@"%@", error);
    }
    [self.typeArr addObjectsFromArray:fetchedObjects];
    [self.tableView reloadData];

}

///这些数据都铺在了tableView上接下来实现删除的操作

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    if (self.titleSegment.selectedSegmentIndex == 0) {
    News *news = self.newsArr[indexPath.row];
    [self.manager.managedObjectContext deleteObject:news];
    [self.manager saveContext];
    [self.newsArr removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }else if (self.titleSegment.selectedSegmentIndex == 1){
    Post *post = self.postArr[indexPath.row];
    [self.manager.managedObjectContext deleteObject:post];
    [self.manager saveContext];
    [self.postArr removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }else if (self.titleSegment.selectedSegmentIndex == 2){
    Forum *forum = self.forumArr[indexPath.row];
    [self.manager.managedObjectContext deleteObject:forum];
    [self.manager saveContext];
    [self.forumArr removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

      }else{
      
          Type *type = self.typeArr[indexPath.row];
          [self.manager.managedObjectContext deleteObject:type];
           [self.manager saveContext];
          [self.typeArr removeObjectAtIndex:indexPath.row];
          [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
      
      }
    

    }
    [self.tableView reloadData];
    }</pre>

    这些就是实现收藏的过程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,752评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,100评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,244评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,099评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,210评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,307评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,346评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,133评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,546评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,849评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,019评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,702评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,331评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,030评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,260评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,871评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,898评论 2 351

推荐阅读更多精彩内容