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;

}

 

你可能感兴趣的:(coredata)