• CoreData数据库搭建


    1.首先创建父类吧重用的代码写在里边

    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    
    @interface DBCenter : NSObject
    
    @property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
    @property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
    @property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
    
    - (NSURL *) modelURL;    //need to be overwrite
    - (NSURL *) storeURL;    //need to be overwrite
    - (NSString *) storeDirectoryPath;
    - (NSString *) entityName;
    - (void) saveContext;
    
    @end
    #import "DBCenter.h"
    
    @interface DBCenter ()
    
    
    @end
    
    @implementation DBCenter
    
    - (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;
        }
        
    //    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"Resources" withExtension:@"bundle"]];
    //    NSURL *modelURL = [bundle URLForResource:@"LECPlayerDataModel" withExtension:@"momd"];
        NSURL *modelURL = [self modelURL];
        
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        return _managedObjectModel;
    }
    
    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
        // The persistent store coordinator for the application. This implementation creates and return 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 storeURL];
        
        NSError *error = nil;
        NSString *failureReason = @"There was an error creating or loading the application's saved data.";
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil 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] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
        return _managedObjectContext;
    }
    
    #pragma mark -
    - (NSURL *) modelURL {
        return nil;
    }
    
    - (NSURL *) storeURL {
        return nil;
    }
    
    - (NSString *) storeDirectoryPath {
        NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *dbDirectory = [documentDirectory stringByAppendingPathComponent:@"DB"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:dbDirectory]) {
            [fileManager createDirectoryAtPath:dbDirectory
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil];
        }
        return dbDirectory;
    }
    
    - (NSString *) entityName {
        return nil;
    }
    
    - (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();
            }
        }
    }
    
    @end

    2.然后对于某一个存储模块独立出来继承

    @interface DBCenterNewsExtend : DBCenter
    
    + (DBCenterNewsExtend *) sharedNewsDBCenter;
    
    /*启动广告*/
    - (LaunchingAdItemModel *) launchingAdItem;
    - (void) fullFillLaunchingAdItemModelWithLaunchingAdItem:(LaunchingAdItem *) launchingAdItem;
    - (void) saveLaunchingAdItemDataModel;
    - (void) removeLaunchingAdItem;
    
    /*新闻阅读记录*/
    - (BOOL) hasReadWithNewsId:(NSString *) newsId;
    - (void) addReadRecordWithNewsId:(NSString *) newsId;
    
    /*新闻收藏记录*/
    - (BOOL) hasFavoriteWithNewsId:(NSString *) newsId;
    - (void) addFavoriteRecordWithNewsDisplayItem:(NewsDisplayItem *) newsDisplayItem;
    - (void) removeFavoriteRecordWithNewsId:(NSString *) newsId;
    - (NSArray *) favoriteNewsList; //NSArray<NewsParamItem>
    
    /*搜索关键字列表*/
    - (void) addSearchKeywordRecord:(NSString *) keyword;
    - (NSArray *) keywordsList; //NSArray<NewsSearchKeywordModel>
    - (void) cleanKeywordsList;
    
    @end
    @interface DBCenterNewsExtend ()
    
    @property (nonatomic, strong) LaunchingAdItemModel *launchingAdItemModel;
    @property (nonatomic, strong) NSMutableArray *mNewsReadRecordsList;
    @property (nonatomic, strong) NSMutableArray *mNewsDisplayModelList;
    @property (nonatomic, strong) NSMutableArray *mNewsDisplayItemList;
    @property (nonatomic, strong) NSMutableArray *mSearchKeywordsList;
    
    - (void) loadLaunchingAdItemModel;
    - (NSString *) launchingAdEntityName;
    
    - (void) loadReadRecordsList;
    - (NSString *) newsReadRecordEntityName;
    - (NewsReadRecordItemModel *) newsReadRecordItemModelWithNewsId:(NSString *) newsId;
    
    - (void) loadFavoriteRecordsList;
    - (NSString *) newsDisplayItemEntityName;
    - (NewsDisplayItem *) newsDisplayItemFromNewsDisplayDataModel:(NewsDisplayItemDataModel *) newsDisplayItemDataModel;
    - (NewsDisplayItemDataModel *) insertNewsDisplayItemDataModelFromNewsDisplayItem:(NewsDisplayItem *) newsDisplayItem;
    - (NewsDisplayItem *) newsDisplayItemWithNewsId:(NSString *) newsId;
    - (NewsDisplayItemDataModel *) newsDisplayItemDataModelWithNewsId:(NSString *) newsId;
    
    - (void) loadSearchKeywordsList;
    - (NSString *) searchKeywordEntityName;
    - (NewsSearchKeywordModel *) searchDataModelWithKeyword:(NSString *) keyword;
    
    @end
    
    @implementation DBCenterNewsExtend
    
    - (id) init {
        if (self = [super init]) {
            [self loadLaunchingAdItemModel];
            [self loadReadRecordsList];
            [self loadFavoriteRecordsList];
            [self loadSearchKeywordsList];
        }
        return self;
    }
    
    #pragma mark -
    #pragma mark Overwrite
    - (NSURL *) modelURL {
        NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"NewsModel" ofType:@"momd"];
        NSURL *modelURL = [NSURL URLWithString:modelPath];
        return modelURL;
    }
    
    - (NSURL *) storeURL {
        NSString *directoryPath = [self storeDirectoryPath];
        NSString *storePath = [directoryPath stringByAppendingPathComponent:@"NewsModel.sqlite"];
        return [NSURL fileURLWithPath:storePath];
    }
    
    
    #pragma mark -
    #pragma mark Public Methods
    + (DBCenterNewsExtend *) sharedNewsDBCenter {
        static DBCenterNewsExtend *newsDBCenter = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            newsDBCenter = [[DBCenterNewsExtend alloc] init];
        });
        return newsDBCenter;
    }
    
    - (LaunchingAdItemModel *) launchingAdItem {
        return _launchingAdItemModel;
    }
    
    - (void) fullFillLaunchingAdItemModelWithLaunchingAdItem:(LaunchingAdItem *) launchingAdItem {
        if (!_launchingAdItemModel) {
            _launchingAdItemModel = [NSEntityDescription insertNewObjectForEntityForName:[self launchingAdEntityName] inManagedObjectContext:self.managedObjectContext];
            [self saveContext];
        }
        _launchingAdItemModel.adId = launchingAdItem.adId;
        _launchingAdItemModel.adTitle = launchingAdItem.adTitle;
        _launchingAdItemModel.adImgUrl = launchingAdItem.adImgUrl;
        _launchingAdItemModel.adWebUrl = launchingAdItem.adWebUrl;
        _launchingAdItemModel.adEndTime = launchingAdItem.adEndTime;
        [self saveContext];
    }
    
    - (void) saveLaunchingAdItemDataModel {
        [self saveContext];
    }
    
    - (void) removeLaunchingAdItem {
        [[self managedObjectContext] deleteObject:_launchingAdItemModel];
        _launchingAdItemModel = nil;
    }
    
    - (BOOL) hasReadWithNewsId:(NSString *) newsId {
        bool hasRead = NO;
        if ([self newsReadRecordItemModelWithNewsId:newsId]) {
            hasRead = YES;
        }
        return hasRead;
    }
    
    - (void) addReadRecordWithNewsId:(NSString *) newsId {
        if (![self newsReadRecordItemModelWithNewsId:newsId]) {
            
            NewsReadRecordItemModel *newsReadRecordItemModel = [NSEntityDescription insertNewObjectForEntityForName:[self newsReadRecordEntityName] inManagedObjectContext:self.managedObjectContext];
            newsReadRecordItemModel.newsId = newsId;
            [_mNewsReadRecordsList addObject:newsReadRecordItemModel];
            [self saveContext];
        }
    }
    
    /*新闻收藏记录*/
    - (BOOL) hasFavoriteWithNewsId:(NSString *) newsId {
        for (NewsDisplayItem *newsDisplayItem in _mNewsDisplayItemList) {
            if (newsDisplayItem.newsDisplayParamItemList.count > 0) {
                NewsDisplayParamItem *displayParamItem = newsDisplayItem.newsDisplayParamItemList[0];
                if ([displayParamItem.newsId isEqualToString:newsId]) {
                    return YES;
                }
            }
        }
        return NO;
    }
    
    - (void) addFavoriteRecordWithNewsDisplayItem:(NewsDisplayItem *) newsDisplayItem {
        NewsDisplayParamItem *newsDisplayParamItem;
        if (newsDisplayItem.newsDisplayParamItemList.count > 0) {
            newsDisplayParamItem = newsDisplayItem.newsDisplayParamItemList[0];
        }
        NSString *newsId = newsDisplayParamItem.newsId;
        if (![self hasFavoriteWithNewsId:newsId]) {
            [self insertNewsDisplayItemDataModelFromNewsDisplayItem:newsDisplayItem];
        }
    }
    
    - (void) removeFavoriteRecordWithNewsId:(NSString *) newsId {
        NewsDisplayItemDataModel *newsDisplayItemDataModel = [self newsDisplayItemDataModelWithNewsId:newsId];
        if (newsDisplayItemDataModel) {
            [[self managedObjectContext] deleteObject:newsDisplayItemDataModel];
            [self saveContext];
        }
        
        NewsDisplayItem *newsDisplayItem = [self newsDisplayItemWithNewsId:newsId];
        if (newsDisplayItem) {
            [_mNewsDisplayItemList removeObject:newsDisplayItem];
        }
    }
    
    - (NSArray *) favoriteNewsList {
        return _mNewsDisplayItemList;
    }
    
    /*搜索关键字列表*/
    - (void) addSearchKeywordRecord:(NSString *) keyword {
        if (![self searchDataModelWithKeyword:keyword]) {
            NewsSearchKeywordModel *newsSearchKeywordModel = [NSEntityDescription insertNewObjectForEntityForName:[self searchKeywordEntityName] inManagedObjectContext:self.managedObjectContext];
            newsSearchKeywordModel.keyword = keyword;
            [_mSearchKeywordsList addObject:newsSearchKeywordModel];
            [self saveContext];
        }
    }
    
    - (NSArray *) keywordsList {
        NSMutableArray *mKeywordList = [[NSMutableArray alloc] init];
        for (NewsSearchKeywordModel *keywordModel in _mSearchKeywordsList) {
            [mKeywordList addObject:keywordModel.keyword];
        }
        return mKeywordList;
    }
    
    - (void) cleanKeywordsList {
        for (NewsSearchKeywordModel *searchKeywordModel in _mSearchKeywordsList) {
            [[self managedObjectContext] deleteObject:searchKeywordModel];
        }
        [_mSearchKeywordsList removeAllObjects];
        [self saveContext];
    }
    
    #pragma mark -
    #pragma mark Public Methods
    - (void) loadLaunchingAdItemModel {
        NSFetchRequest* request=[[NSFetchRequest alloc] init];
        NSEntityDescription* userItemDataModelDescription = [NSEntityDescription entityForName:[self launchingAdEntityName] inManagedObjectContext:self.managedObjectContext];
        [request setEntity:userItemDataModelDescription];
        NSArray* fetchResultList = [self.managedObjectContext executeFetchRequest:request error:nil];
        if (fetchResultList.count > 0) {
            _launchingAdItemModel = fetchResultList[0];
        }
    }
    
    - (NSString *) launchingAdEntityName {
        return @"LaunchingAdItemModel";
    }
    
    - (void) loadReadRecordsList {
        NSFetchRequest* request=[[NSFetchRequest alloc] init];
        NSEntityDescription* userItemDataModelDescription = [NSEntityDescription entityForName:[self newsReadRecordEntityName] inManagedObjectContext:self.managedObjectContext];
        [request setEntity:userItemDataModelDescription];
        NSArray* fetchResultList = [self.managedObjectContext executeFetchRequest:request error:nil];
        _mNewsReadRecordsList = [NSMutableArray arrayWithArray:fetchResultList];
    }
    
    - (NSString *) newsReadRecordEntityName {
        return @"NewsReadRecordItemModel";
    }
    
    - (NewsReadRecordItemModel *) newsReadRecordItemModelWithNewsId:(NSString *) newsId {
        for (NewsReadRecordItemModel *newsReadRecordItemModel in _mNewsReadRecordsList) {
            if ([newsReadRecordItemModel.newsId isEqualToString:newsId]) {
                return newsReadRecordItemModel;
            }
        }
        return nil;
    }
    
    - (void) loadFavoriteRecordsList {
        _mNewsDisplayModelList = [[NSMutableArray alloc] init];
        _mNewsDisplayItemList = [[NSMutableArray alloc] init];
    
        NSFetchRequest* request=[[NSFetchRequest alloc] init];
        NSEntityDescription* userItemDataModelDescription = [NSEntityDescription entityForName:[self newsDisplayItemEntityName] inManagedObjectContext:self.managedObjectContext];
        [request setEntity:userItemDataModelDescription];
        NSArray* fetchResultList = [self.managedObjectContext executeFetchRequest:request error:nil];
        _mNewsDisplayModelList = [NSMutableArray arrayWithArray:fetchResultList];
    
        for (NewsDisplayItemDataModel *newsDisplayItemDataModel in _mNewsDisplayModelList) {
            NewsDisplayItem *newsDisplayItem = [self newsDisplayItemFromNewsDisplayDataModel:newsDisplayItemDataModel];
            [_mNewsDisplayItemList addObject:newsDisplayItem];
        }
    }
    
    - (NSString *) newsDisplayItemEntityName {
        return @"NewsDisplayItemDataModel";
    }
    
    - (NewsDisplayItem *) newsDisplayItemFromNewsDisplayDataModel:(NewsDisplayItemDataModel *) newsDisplayItemDataModel {
        NewsDisplayItem *newsDisplayItem = [[NewsDisplayItem alloc] init];
        newsDisplayItem.displayType = [newsDisplayItemDataModel.displayType integerValue];
        newsDisplayItem.subscriptType = [newsDisplayItemDataModel.subscriptType integerValue];
        
        NewsDisplayParamItem *newsDisplayParamItem = [[NewsDisplayParamItem alloc] init];
        newsDisplayParamItem.newsId = newsDisplayItemDataModel.newsId;
        newsDisplayParamItem.newsTitle = newsDisplayItemDataModel.newsTitle;
        newsDisplayParamItem.newsBrief = newsDisplayItemDataModel.newsBrief;
        newsDisplayParamItem.newsDetailType = [newsDisplayItemDataModel.newsDetailType integerValue];
        newsDisplayParamItem.imagesList = [newsDisplayItemDataModel.newsImageList componentsSeparatedByString:@" "];
    
        newsDisplayItem.newsDisplayParamItemList = @[newsDisplayParamItem];
        
        return newsDisplayItem;
    }
    
    - (NewsDisplayItemDataModel *) insertNewsDisplayItemDataModelFromNewsDisplayItem:(NewsDisplayItem *) newsDisplayItem {
        NewsDisplayItemDataModel *newsDisplayItemDataModel = [NSEntityDescription insertNewObjectForEntityForName:[self newsDisplayItemEntityName] inManagedObjectContext:self.managedObjectContext];
        newsDisplayItemDataModel.displayType = @(newsDisplayItem.displayType);
        newsDisplayItemDataModel.subscriptType = @(newsDisplayItem.subscriptType);
        
        if (newsDisplayItem.newsDisplayParamItemList.count > 0) {
            NewsDisplayParamItem *newsDisplayParamItem = newsDisplayItem.newsDisplayParamItemList[0];
            
            newsDisplayItemDataModel.newsId = newsDisplayParamItem.newsId;
            newsDisplayItemDataModel.newsBrief = newsDisplayParamItem.newsBrief;
            newsDisplayItemDataModel.newsDetailType = @(newsDisplayParamItem.newsDetailType);
            newsDisplayItemDataModel.newsTitle = newsDisplayParamItem.newsTitle;
            
            NSMutableString *newsImageListString = [[NSMutableString alloc] init];
            for (int i = 0; i < newsDisplayParamItem.imagesList.count; i++) {
                NSString *imageUrl = newsDisplayParamItem.imagesList[i];
                [newsImageListString appendString:imageUrl];
                if (i < newsDisplayParamItem.imagesList.count - 1) {
                    [newsImageListString appendString:@" "];
                }
            }
            newsDisplayItemDataModel.newsImageList = newsImageListString;
        }
        
        [_mNewsDisplayModelList addObject:newsDisplayItemDataModel];
        [_mNewsDisplayItemList addObject:newsDisplayItem];
        
        [self saveContext];
    
        return newsDisplayItemDataModel;
    }
    
    - (NewsDisplayItem *) newsDisplayItemWithNewsId:(NSString *) newsId {
        for (NewsDisplayItem *newsDisplayItem in _mNewsDisplayItemList) {
            if (newsDisplayItem.newsDisplayParamItemList.count > 0) {
                NewsDisplayParamItem *displayParamItem = newsDisplayItem.newsDisplayParamItemList[0];
                if ([displayParamItem.newsId isEqualToString:newsId]) {
                    return newsDisplayItem;
                }
            }
        }
        return nil;
    }
    
    - (NewsDisplayItemDataModel *) newsDisplayItemDataModelWithNewsId:(NSString *) newsId {
        for (NewsDisplayItemDataModel *newsDisplayItemDataModel in _mNewsDisplayModelList) {
            if ([newsDisplayItemDataModel.newsId isEqualToString:newsId]) {
                return newsDisplayItemDataModel;
            }
        }
        return nil;
    }
    
    - (void) loadSearchKeywordsList {
        NSFetchRequest* request=[[NSFetchRequest alloc] init];
        NSEntityDescription* keywordModelDescription = [NSEntityDescription entityForName:[self searchKeywordEntityName] inManagedObjectContext:self.managedObjectContext];
        [request setEntity:keywordModelDescription];
        NSArray* fetchResultList = [self.managedObjectContext executeFetchRequest:request error:nil];
        _mSearchKeywordsList = [NSMutableArray arrayWithArray:fetchResultList];
    }
    
    - (NSString *) searchKeywordEntityName {
        return @"NewsSearchKeywordModel";
    }
    
    - (NewsSearchKeywordModel *) searchDataModelWithKeyword:(NSString *) keyword {
        for (NewsSearchKeywordModel *newsSearchKeywordModel in _mSearchKeywordsList) {
            if ([newsSearchKeywordModel.keyword isEqualToString:keyword]) {
                return newsSearchKeywordModel;
            }
        }
        return nil;
    }
    
    @end
  • 相关阅读:
    VMware安装最新版CentOS7图文教程
    git 本地给远程仓库创建分支 三步法
    git如何利用分支进行多人开发
    题解 洛谷P6478 [NOI Online #2 提高组] 游戏
    题解 CF1146D Frog Jumping
    题解 洛谷P6477 [NOI Online #2 提高组] 子序列问题
    题解 LOJ2472 「九省联考 2018」IIIDX
    题解 CF1340 A,B,C Codeforces Round #637 (Div. 1)
    题解 LOJ3284 「USACO 2020 US Open Platinum」Exercise
    windows上的路由表
  • 原文地址:https://www.cnblogs.com/keyan1102/p/4548722.html
Copyright © 2020-2023  润新知