CoreDataDemo

17891 단어 coredata
//  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;

}


좋은 웹페이지 즐겨찾기