วันศุกร์ที่ 19 พฤศจิกายน พ.ศ. 2553

CoreData Basic CRUD

ต่อจาก Entry ที่แล้ว นะครับ

สำหรับ Entry นี้จะเป็นเรื่องของ CRUD (Create Read Update Delete) นะครับ
โดยจะต่อจาก Entry ที่แล้วนะครับ

จาก Entry ที่แล้วเราสามารถนำข้อมูลเข้า CoreData ได้แล้ว

-(IBAction) addNew{
MyEntity *myEntity = (MyEntity *)[NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" 
inManagedObjectContext:managedObjectContext];
myEntity.name = _name.text;
NSError *error;
if (![managedObjectContext save:&error]) {
//Handle the error.
}
}

ครั้งนี้เราจะเริ่มจากการนำข้อมูลออกมาแสดงนะครับ
โดยเริ่มผมจะแสดงข้อมูลใน UITableView นะครับ

ขั้นแรกเราก็ทำการสร้าง UITableView ขึ้นมาก่อนนะครับ
เปิด File MainViewController.h

#import <UIKit/UIKit.h>
#import "MyEntity.h"

@interface MainViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { // <<<< Add Protocol. 
IBOutlet UITextField *_name;
NSManagedObjectContext *managedObjectContext
UITableView *_tableView; // <<<< Add This Line.
}

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

-(IBAction) addNew;
-(IBAction) showData;

@end



สำหรับเรื่องของ UITableView คราวหน้าจะมาเขียนให้นะครับ
คร่าวๆ คือต้องสร้าง tableView และทำการประกาศ Protocol 2 ตัว (เป็นเรื่องของ Delegate Method ลองหาอ่านเพิ่มเติมได้ครับ) 
สร้าง tableView จาก UITableView และมี Protocol ที่เกี่ยวข้องคือ UITableViewDelegate และ UITableViewDataSource

หลังจากนั้นไปที่ MainViewController.m
ทำการสร้าง Table 

- (void)viewDidLoad {
    [super viewDidLoad];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 300, 400) style:UITableViewStylePlain]; // <<<< Add This Line.
_tableView.center = self.view.center; // <<<< Add This Line.
_tableView.delegate = self; // <<<< Add This Line.
_tableView.dataSource = self; // <<<< Add This Line.
[self.view addSubview:_tableView]; // <<<< Add This Line.
}



เพิ่ม Method สำหรับการ Get ข้อมูล (ในที่นี้ให้เป็น Method ที่ใช้งานภายใน Class MainViewController)

#import "MainViewController.h"

@interface MainViewController (Private)

-(NSArray *)getData;

@end


@implementation MainViewController

@synthesize managedObjectContext; 

-(NSArray *)getData{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" 
  inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[request release];
return [mutableFetchResults autorelease];
}



ทำการ Implement method ของ UITableViewDelegate และ UITableViewDataSource
เพิ่ม Code ใน MainViewController.m

#pragma mark -
#pragma mark UITableViewDelegate And UITableViewDataSource

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"entityCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"entityCell"] autorelease];
}
cell.textLabel.text = ((MyEntity *)[[self getData] objectAtIndex:indexPath.row]).name;
return cell;
}

-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [[self getData] count];
}



ต่อไปการลบข้อมูลนะครับ
ทำการเพิ่ม Method

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObject *entityToDelete = [[self getData] objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:entityToDelete];
        NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
}



ใน Method addNew เพิ่ม [_tableView reloadData]; หลังจากเพิ่มข้อมูล

-(IBAction) addNew{
MyEntity *myEntity = (MyEntity *)[NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" 
inManagedObjectContext:managedObjectContext];
myEntity.name = _name.text;
NSError *error;
if (![managedObjectContext save:&error]) {
//Handle the error.
}
[_tableView reloadData]; // <<<< Add This Line.
}



เรื่องการ Update เพิ่ม Action สำหรับ Update ใน MainViewController.h

#import <UIKit/UIKit.h>
#import "MyEntity.h"

@interface MainViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { 
IBOutlet UITextField *_name;
NSManagedObjectContext *managedObjectContext
UITableView *_tableView

NSIndexPath *_currentSelect; // <<<< Add This Line.
}

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

-(IBAction) addNew;
-(IBAction) showData;

-(IBAction) update; // <<<< Add This Line.

@end




เพิ่มปุ่ม Update ใน Interface Builder โดยเปิด MainViewController.xib



เชื่อมปุ่ม Update กับ Action update (ctrl+ลาก)

ไปที่ MainViewController.m

เพิ่ม Method update และแก้ไข Code ที่ Method 
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

เพิ่ม Code 

-(IBAction) update{
NSManagedObject *selectObject = ((MyEntity *)[[self getData] objectAtIndex:_currentSelect.row]);
((MyEntity *)selectObject).name = _name.text;
NSError *error;
if (![managedObjectContext save:&error]) {
//Handle the error.
}
[_tableView reloadData];
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_currentSelect = indexPath;
_name.text = ((MyEntity *)[[self getData] objectAtIndex:indexPath.row]).name;
}



Build And Run

หลังจากเลือกข้อมูลใน Table จะสามารถแก้ไขข้อมูลโดยแก้ไขที่ช่องใส่ข้อมูล




1 ความคิดเห็น:

  1. แจ่มแจ้งครับ บาสเข้าใจทั้งหมดแล้ว เหลือปัญหาคาใจอีกนิดหน่อย
    แต่เดี๋ยวไว้เจอ @rawitat แล้วค่อยถามครับ...

    สนุกดีเหมือนกันครับ การ setupview ด้วย code เนี่ย นี่ก็พึ่งลองได้ 2 ครั้งเอง ต้องหัดให้คล่องกว่านี้หน่อย

    ตอบลบ