一般做收藏都是使用数据库或者归档,使用CoreData实现收藏功能就是没事时练一下,实现大概和数据库差不多.

首先创建一个工具类继承NSObject,在里面实现所需要的方法.

  工具类的.h文件:

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
    工具类的.m文件

@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
  接下来在收藏页面创建一个Button实现收藏

- (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];
}
      这些就是实现收藏的过程

iOS使用CoreData实现收藏功能的更多相关文章

  1. 改进iOS客户端的升级提醒功能

    改进iOS客户端的升级提醒功能 功能设计 先申明一下,我是码农,不是一个产品经理,但我觉得现有市面上的很多 App,设计的 "升级提示功能" 都不太友好.在此分享一下我的想法,欢迎 ...

  2. Yii中Ajax的使用,如收藏功能

    view中 <?php $cs=Yii::app()->clientScript; $cs->registerScriptFile('http://ajax.googleapis.c ...

  3. iOS 用UISearchDisplayController实现查找功能

    UISearchDisplayController是iOS中用于处理搜索功能的控制器,此控制器需要和UISearchBar结合使用 示例代码如下: // // WKRootViewController ...

  4. iOS Swift WisdomScanKit图片浏览器功能SDK

    iOS Swift WisdomScanKit图片浏览器功能SDK使用 一:简介      WisdomScanKit 由 Swift4.2版编写,完全兼容OC项目调用. WisdomScanKit的 ...

  5. iOS蓝牙BLE4.0通信功能

    概述 iOS蓝牙BLE4.0通信功能,最近刚学的苹果,为了实现蓝牙门锁的项目,找了一天学习了下蓝牙的原理,亲手测试了一次蓝牙的通信功能,结果成功了,那么就把我学习的东西分享一下. 详细 代码下载:ht ...

  6. 【Android】3.21 示例21—兴趣点收藏功能

    分类:C#.Android.VS2015.百度地图应用: 创建日期:2016-02-04 简介:介绍如何创建.管理本地收藏的兴趣点数据 详述: (1)新建本地点收藏: (2)查看已收藏本地点: (3) ...

  7. mxonline实战9,我要学习功能块,机构详情展示,收藏功能

    对应github地址:第9天   一. 实现我要学习功能

  8. 18、Django实战第18天:课程机构收藏功能

    这里点击"收藏"也是ajax异步操作,我在operation.model.py中创建了一个用户收藏表,其中fav_id字段,如果我们收藏的是课程,那就是课程id,如果收藏的是课程机 ...

  9. ios开发视频播放后台下载功能实现 :1,ios播放视频 ,包含基于AVPlayer播放器,2,实现下载,iOS后台下载(多任务同时下载,单任务下载,下载进度,下载百分比,文件大小,下载状态)(真机调试功能正常)

    ABBPlayerKit ios开发视频播放后台下载功能实现 : 代码下载地址:https://github.com/niexiaobo/ABBPlayerKit github资料学习和下载地址:ht ...

随机推荐

  1. HTML5学习之新增标签

    转自:http://www.cnblogs.com/fly_dragon/archive/2012/05/25/2516142.html 作者:FlyDragon 一.引言 在本节中,笔者将向大家讲述 ...

  2. JSON.parse() 和 JSON.stringify()使用

    1.parse()是用于从一个字符串中解析出json对象 定义一个字符串:var str = '{"name":"superman","age&quo ...

  3. Lesson 2

    周末重新学习了一下java,有了些新的体会 1.关于jdk, jre,and  JVM: Jdk: java development kit,面向开发人员的java开发工具包 Jre:java run ...

  4. L2-001. 紧急救援---(Dijkstra,记录路径)

    https://www.patest.cn/contests/gplt/L2-001 L2-001. 紧急救援 时间限制 200 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 ...

  5. Flink源码阅读(一)--Checkpoint触发机制

    Checkpoint触发机制 Flink的checkpoint是通过定时器周期性触发的.checkpoint触发最关键的类是CheckpointCoordinator,称它为检查点协调器. org.a ...

  6. UNREFERENCED_PARAMETER()的作用

    告诉编译器,已经使用了该变量,不必警告. 在VC编译器下,当你声明了一个变量,而没有使用时,编译器就会报警告: “warning C4100: ''XXXX'' : unreferenced form ...

  7. [Leetcode Week3]Clone Graph

    Clone Graph题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/clone-graph/description/ Description Clon ...

  8. UVALIVE 3486 Cells

    通过入栈出栈顺序判断祖先关系 这里UVALIVE还 #include <map> #include <set> #include <list> #include & ...

  9. 《Java编程思想》笔记 第二章 一切都是对象

    1.对象存储位置 对象的引用存在栈中,对象存在堆中.new 出来的对象都在堆中存储.栈的存取速度较快. 所有局部变量都放在栈内存里,不管是基本类型变量还是引用类型变量,都存储在各自的方法栈中: 但是引 ...

  10. java使用maven项目(二)分模块开发

    1       整合ssh框架 1.1     依赖传递 只添加了一个struts2-core依赖,发现项目中出现了很多jar, 这种情况 叫 依赖传递 1.2     依赖版本冲突的解决 1.  第 ...