CoreDataDemo
// User.h
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> @interface User : NSManagedObject @property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSData * headImage; @end // User.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "User.h" @implementation User @dynamic name;
@dynamic age;
@dynamic headImage; @end // Address.h
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> @interface Address : NSManagedObject @end // Address.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "Address.h" @implementation Address @end
//
// DBManager.h
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import <Foundation/Foundation.h>
#import "User.h" @interface DBManager : NSObject //获取单例类型对象
+ (DBManager *)sharedManager; //增加的操作
- (void)insertUser:(NSDictionary *)userDict; //查询的方法
- (NSArray *)searchAllUsers; //修改的方法
- (void)updateUserWithName:(NSString *)name dict:(NSDictionary *)userDict; //删除的方法
- (void)deleteUser:(User *)user; @end //
// DBManager.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "DBManager.h"
#import <CoreData/CoreData.h> @implementation DBManager
{
NSManagedObjectContext *_dbContext;
} +(DBManager *)sharedManager
{
static DBManager *manager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ manager = [[DBManager alloc] init]; }); return manager;
} -(instancetype)init
{
self = [super init];
if (self) { //创建coreData的相应对象
[self createContext]; } return self;
} - (NSManagedObjectModel *)createModel
{ NSString *path = [[NSBundle mainBundle] pathForResource:@"MyUser" ofType:@"momd"]; NSURL *url = [NSURL fileURLWithPath:path]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url]; return model; } - (NSPersistentStoreCoordinator *)createCoordinateWithModel:(NSManagedObjectModel *)model
{
NSPersistentStoreCoordinator *coor = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; return coor;
} - (void)addStore:(NSPersistentStoreCoordinator *)coor
{
//第一个参数:文件的类型(sqlite、xml、binary)
//第二个参数:nil
//第三个参数:sqlite文件的路径
//第四个参数:nil
//第五个参数:错误信息 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/user.sqlite"]; NSLog(@"path:%@",path); NSURL *url = [NSURL fileURLWithPath:path]; NSError *error; NSPersistentStore *store = [coor addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]; if (error) {
NSLog(@"error:%@",error.localizedDescription);
} } - (void)createContext
{
//1.NSManagedObjectModel
NSManagedObjectModel *model = [self createModel]; //2.NSPersistentStoreCoordinator
NSPersistentStoreCoordinator *coor = [self createCoordinateWithModel:model]; //3.NSPersistentStore
[self addStore:coor]; //4.NSManagedObjectContext
_dbContext = [[NSManagedObjectContext alloc] init];
_dbContext.persistentStoreCoordinator = coor; } -(void)insertUser:(NSDictionary *)userDict
{
//第一个参数:类名
User *newUser = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:_dbContext]; //给newUser对象属性赋值
if ([userDict objectForKey:@"name"]) {
newUser.name = userDict[@"name"];
} if (userDict[@"age"]) {
newUser.age = userDict[@"age"];
} if (userDict[@"headImage"]) {
newUser.headImage = userDict[@"headImage"];
} //保存
NSError *error;
[_dbContext save:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
} } //查询的方法
- (NSArray *)searchAllUsers
{ NSEntityDescription *desc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:_dbContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = desc; //执行查询
NSError *error;
NSArray *userArray = [_dbContext executeFetchRequest:request error:&error]; if (error) {
NSLog(@"%@",error.localizedDescription);
} return userArray; } //修改的方法
- (void)updateUserWithName:(NSString *)name dict:(NSDictionary *)userDict
{
//先查询出来满足条件的
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *desc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:_dbContext];
request.entity = desc; //查询条件
//谓词
NSPredicate *predict = [NSPredicate predicateWithFormat:@"name == %@",name]; request.predicate = predict; NSError *error;
NSArray *userArray = [_dbContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"%@",error);
} //修改
for (User *tmpUser in userArray) { if (userDict[@"name"]) {
tmpUser.name = userDict[@"name"];
}
if (userDict[@"age"]) {
tmpUser.age = userDict[@"age"];
}
if (userDict[@"headImage"]) {
tmpUser.headImage = userDict[@"headImage"];
} } //保存
NSError *updateError;
[_dbContext save:&updateError]; if (updateError) {
NSLog(@"updateError:%@",updateError.localizedDescription);
} } //删除
- (void)deleteUser:(User *)user
{
[_dbContext deleteObject:user]; //保存
NSError *error;
[_dbContext save:&error]; if (error) {
NSLog(@"%@",error.localizedDescription);
} } @end
// DetailViewController.h
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import <UIKit/UIKit.h>
#import "User.h" @interface DetailViewController : UIViewController //当前的用户信息
@property (nonatomic,strong)User *user; @end //
// DetailViewController.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "DetailViewController.h"
#import "DBManager.h" @interface DetailViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate> @end @implementation DetailViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view. self.view.backgroundColor = [UIColor whiteColor]; //保存按钮
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(saveAction:)];
self.navigationItem.rightBarButtonItem = rightItem; //显示详细信息
//姓名
UILabel *nameLabel = [self createLabelFrame:CGRectMake(30, 100, 60, 40) text:@"姓名:"];
UITextField *nameTextField = [self createTextField:CGRectMake(110, 100, 200, 40) placeHolder:@"请输入姓名"];
nameTextField.tag = 100; [self.view addSubview:nameLabel];
[self.view addSubview:nameTextField]; //年龄
UILabel *ageLabel = [self createLabelFrame:CGRectMake(30, 160, 60, 40) text:@"年龄:"];
UITextField *ageTextField = [self createTextField:CGRectMake(110, 160, 200, 40) placeHolder:@"请输入年龄"];
ageTextField.tag = 200; [self.view addSubview:ageLabel];
[self.view addSubview:ageTextField]; //头像
UILabel *imageLabel = [self createLabelFrame:CGRectMake(30, 220, 60, 40) text:@"头像:"];
UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
imageBtn.frame = CGRectMake(110, 220, 200, 200);
[imageBtn addTarget:self action:@selector(chooseImage:) forControlEvents:UIControlEventTouchUpInside];
imageBtn.tag = 300; [self.view addSubview:imageLabel];
[self.view addSubview:imageBtn]; //显示
if (self.user) {
nameTextField.text = self.user.name; ageTextField.text = [NSString stringWithFormat:@"%@",self.user.age]; [imageBtn setBackgroundImage:[UIImage imageWithData:self.user.headImage] forState:UIControlStateNormal]; } } - (void)chooseImage:(id)sender
{
//从相册选择图片
UIImagePickerController *ctrl = [[UIImagePickerController alloc] init];
ctrl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
ctrl.delegate = self; [self presentViewController:ctrl animated:YES completion:nil]; } #pragma mark - UIImagePickerController代理
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
} -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = info[UIImagePickerControllerOriginalImage]; //取到显示头像的按钮
UIButton *imageBtn = (UIButton *)[self.view viewWithTag:300];
[imageBtn setBackgroundImage:image forState:UIControlStateNormal]; [picker dismissViewControllerAnimated:YES completion:nil]; } //创建label的方法
- (UILabel *)createLabelFrame:(CGRect)frame text:(NSString *)text
{
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = text; return label; } //创建textField的方法
- (UITextField *)createTextField:(CGRect)frame placeHolder:(NSString *)placeHolder
{
UITextField *textField = [[UITextField alloc] initWithFrame:frame];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.placeholder = placeHolder; return textField; } //保存
- (void)saveAction:(id)sender
{
UITextField *nameTextField = (UITextField *)[self.view viewWithTag:100]; UITextField *ageTextField = (UITextField *)[self.view viewWithTag:200]; UIButton *imageBtn = (UIButton *)[self.view viewWithTag:300]; //添加的功能
NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
if (nameTextField.text.length > 0) {
[userDict setObject:nameTextField.text forKey:@"name"];
}
if (ageTextField.text.length > 0) { NSNumber *age = [NSNumber numberWithInt:[ageTextField.text intValue]]; [userDict setObject:age forKey:@"age"];
} UIImage *image = [imageBtn backgroundImageForState:UIControlStateNormal];
NSData *data = UIImagePNGRepresentation(image); if (data.length > 0) {
[userDict setObject:data forKey:@"headImage"];
} if (self.user) { //修改数据
[[DBManager sharedManager] updateUserWithName:self.user.name dict:userDict]; }else{ //添加一条数据
[[DBManager sharedManager] insertUser:userDict];
} [self.navigationController popViewControllerAnimated:YES]; } - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} /*
#pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/ @end
// ViewController.h
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end //
// ViewController.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "ViewController.h"
#import "DetailViewController.h"
#import "DBManager.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *_dataArray; UITableView *_tbView;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. //初始化数据源
_dataArray = [NSMutableArray array]; //创建表格视图
self.automaticallyAdjustsScrollViewInsets = NO;
_tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 375, 667-64) style:UITableViewStylePlain];
_tbView.delegate = self;
_tbView.dataSource = self;
[self.view addSubview:_tbView]; //添加按钮
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(myAddAction:)];
self.navigationItem.rightBarButtonItem = rightItem; self.view.backgroundColor = [UIColor whiteColor];
} - (void)myAddAction:(id)sender
{
DetailViewController *dvc = [[DetailViewController alloc] init]; [self.navigationController pushViewController:dvc animated:YES]; } - (void)searchUsersFromCoreData
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSArray *userArray = [[DBManager sharedManager] searchAllUsers]; if (userArray.count > 0) {
_dataArray = [NSMutableArray arrayWithArray:userArray];
} //刷新表格
dispatch_async(dispatch_get_main_queue(), ^{
[_tbView reloadData];
}); });
} -(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated]; [self searchUsersFromCoreData]; } - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} #pragma mark - UITableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"cellID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
} //取到数据模型
User *user = _dataArray[indexPath.row]; cell.imageView.image = [UIImage imageWithData:user.headImage]; cell.textLabel.text = user.name; cell.detailTextLabel.text = [NSString stringWithFormat:@"年龄:%@",user.age]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *dvc = [[DetailViewController alloc] init]; dvc.user = _dataArray[indexPath.row]; [self.navigationController pushViewController:dvc animated:YES];
} - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) { //删除
User *user = _dataArray[indexPath.row]; [[DBManager sharedManager] deleteUser:user]; [_dataArray removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; }
} @end
// AppDelegate.m
// CoreDataDemo
//
// Created by gaokunpeng on 15/2/4.
// Copyright (c) 2015年 qianfeng. All rights reserved.
// #import "AppDelegate.h"
#import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch. //创建一个导航视图控制器
ViewController *vCtrl = [[ViewController alloc] init]; UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:vCtrl]; self.window.rootViewController = navCtrl; return YES;
}
CoreDataDemo的更多相关文章
- iOS CoreData 增删改查详解
最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...
- Objective-c CoreData
#import "AppDelegate.h" #import "Person.h" @implementation AppDelegate @synthesi ...
- iOS CoreData(2)
上面一篇文章介绍了coredata的有关基本概念,由于大部分是参考别人文章中的内容,所以感觉有点虚,而且估计也是比较难以理解,下面这篇文章通俗一点说说学习coredata后的一些理解,然后给出一个简单 ...
- iOS学习笔记-CoreData
简介 CoreData提供了对象关系映射(ORM)功能,从效果上说就是创建了一个"虚拟对象数据库",也可以把它看作一个综合的数据库管理库. NSManagedObjectConte ...
- iOS-Core Data基础
Core Data基础 Core Data是一个API集合,被设计用来简化数据对象的持久存储. 在此先不普及概念,先通过一个简单的案例使用来感受一下Core Data的精妙之处. 在创建工程的时候勾选 ...
- ios之coredata(二)
上面一篇文章介绍了coredata的有关基本概念,由于大部分是参考别人文章中的内容,所以感觉有点虚,而且估计也是比较难以理解,下面这篇文章通俗一点说说学习coredata后的一些理解,然后给出一个简单 ...
- CoreData 从入门到精通 (一) 数据模型 + CoreData 栈的创建
CoreData 是 Cocoa 平台上用来管理模型层数据和数据持久化的一个框架,说简单点,就是一个数据库存储框架.CoreData 里相关的概念比较多,而且初始化也非常繁琐,所以对初学者的学习还是有 ...
随机推荐
- Python 实现「食行生鲜」签到领积分
用过食行生鲜的同学应该知道,每天可以在食行生鲜签到,签到可以领到 20 积分,在购物时可以抵 2 毛钱.钱虽少,但是积少成多,买菜时可以抵扣一两块钱还是不错的. 今天我们就用 Python 来实现自动 ...
- 【LeetCode】017. Letter Combinations of a Phone Number
题目: Given a digit string, return all possible letter combinations that the number could represent. A ...
- Ubuntu 获得超级用户权限
sudo passwd root 首先要先输入当前用户的密码,再在"输入新的UNIX密码"后面输入你想要设置的 root 密码即可,然后就可以切换到 super user 了: $ ...
- nohup开机自启脚本
#!/bin/bash cd /root/xcloud/ str=$"/n" sstr=$(echo -e $str) nohup ./deploy >>/dev/nu ...
- Linux命令总结_命令执行顺序
有时候,我们需要一个命令执行完之后再去执行另一个命令,使用 &&和 ||可以完成 这样的功能,相应的命令可以是系统命令或shell脚本 Shell还提供了在当前shell或子shell ...
- asn编译常见报错
TypeError: unsupported operand type(s) for -: 'str' and 'int' 可能是该用列表的地方没用列表. 1. ’-‘不支持,需改为'_' asn1t ...
- 32.Docker安装MongoDb
从hub.docker.com上去找镜像 阿里云的国内的镜像地址 填上去之后,然后重启下docker就可以了 docker images列出本地的镜像 拉取mango的镜像 运行这个镜像 docker ...
- windows64下安装MySQLdb连接数据库
MySQLdb是Python连接MySQL的模块,下面介绍一下源码方式安装MySQLdb: 1.首先要下载:http://www.codegood.com/downloads,由于我的python是2 ...
- C++ Queues(队列)
C++ Queues(队列) C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构.1.back() 返回一个引用,指向最后一个元素2.empty() 如果队列空则返回真3.fr ...
- 注册美国iTunes账号步骤(跳过绑定银行卡)
步骤: 将iTunes客户端升级到最新版本 注销当前登陆的用户,随便搜索一个免费的应用 点击下载,此时会弹框提示你登陆,点击下方注册超链 跳转到注册页面,同意各种条款,点击下一步 填写邮箱(最好用gm ...