iOS10 coreData简单使用

创建项目需要勾选上use coredata
在自动生成的文件里添加需要的列,
这里写图片描述
把项目改为不使用自动生成,
这里写图片描述
然后点edit里的create nsmanageObject...

在AppDelegate里需要写的代码

给delegate添加三个属性,coredata的模型,上下文,和永久存储助手

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [self persistentContainer];
    return YES;
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"__"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {

                NSLog(@"%@",storeDescription);
                if (error != nil) {


                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    _model = _persistentContainer.managedObjectModel;
    _context = _persistentContainer.viewContext;
    _storeCoor = _persistentContainer.persistentStoreCoordinator;

    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {


        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

把txt的文字成功保存在sql中

//
//  ViewController.m
//  数据
//
//  Created by MrWu on 2017/2/13.
//  Copyright © 2017年 TTYL. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "POSTCODE+CoreDataClass.h"
#import "POSTCODE+CoreDataProperties.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSArray *datasource;
@property (nonatomic, strong) UISearchBar *searchBar;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self readData];
}

- (void)readData {
     AppDelegate *del = [UIApplication sharedApplication].delegate;

    NSFetchRequest *request = [NSFetchRequest
                               fetchRequestWithEntityName:@"POSTCODE"];
    request.sortDescriptors = @[
                                [NSSortDescriptor
                                 sortDescriptorWithKey:@"province" ascending:NO],
                                [NSSortDescriptor
                                 sortDescriptorWithKey:@"city" ascending:NO],
                                [NSSortDescriptor
                                 sortDescriptorWithKey:@"district" ascending:NO]];

    NSError *error = nil;
    NSArray *data = [del.context executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"%@",error);
    }

    if (!data || [data isKindOfClass:[NSArray class]] || [data count] <= 0) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{



        NSString *path = [[NSBundle mainBundle] pathForResource:@"城市邮编最终整理_方便导入数据库" ofType:@"txt"];

        NSString *contentStr = [NSString stringWithContentsOfFile:path encoding:NSUTF16StringEncoding error:nil];

        NSArray *info = [contentStr componentsSeparatedByString:@"\n"];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"POSTCODE" inManagedObjectContext:del.context];

        //给模型对象赋值
        for (NSString *line in info) {
            NSArray *items = [line componentsSeparatedByString:@"\t"];

            //创建模型对象
            POSTCODE *code = [[POSTCODE alloc] initWithEntity:entity insertIntoManagedObjectContext:del.context];

            code.id = items[0];
            code.province = items[1];
            code.city = items[2];
            code.district = items[3];
            code.cityId = ((NSString *)items[4]).length >=4 ? items[4]:[@"0" stringByAppendingString:items[4]];
            code.postCode = items[5];

        }
          [del saveContext];

            NSError *error = nil;;
        NSArray *data_in_db = [del.context executeFetchRequest:request error:&error];

        self.datasource = data_in_db;
       });
    } else {
        self.datasource = data;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值