1.新建一个使用Core Data 的Project
2.在 Core_Data____.xcdatamodeld 文件中创建一个 Person 实体和 Person 类的三个属性 age,firstName,lastName,如下:
3.将创建的Person类实例化为类文件,
(1)创建一个新文件,如图,
(2)这一步做完后,Xcode就会为你创建好一个Person.h 和一个Person.m 文件。
4.你工程里,创建两个视图控制器,两个都是UIViewController的子类,分别命名为PersonListViewController和AddPersonViewController。创建的这两个视图控制器时不带Xib文件的(我们不需要Interface Builder,因为我们UI很简单)。
5.设置PersonListViewController为根控制器,在AppDelegate.h 和 AppDelegate.m 文件中做如下修改:
AppDelegate.h
@property (nonatomic,strong) PersonListViewViewController *personListViewController;
@property (nonatomic, strong) UINavigationController *navigationController;
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.personListViewController = [[PersonListViewViewController alloc] initWithNibName:nil bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.personListViewController];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.window.rootViewController = self.navigationController;
return YES;
}
6.接下来就是PersonListViewController和AddPersonViewController文件的实现,代码也不是特别难看懂,就直接贴上来了。
PersonListViewController.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface PersonListViewViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate>
@property(nonatomic, strong) UITableView *tableViewPersons;
@property(nonatomic, strong) UIBarButtonItem *barButtonAddPerson;
@property(nonatomic, strong) NSFetchedResultsController *personsFRC;
@end
PersonListViewController.m
#import "PersonListViewViewController.h"
#import "AddPersonViewController.h"
#import "AppDelegate.h"
#import "Person.h"
@interface PersonListViewViewController ()
@end
@implementation PersonListViewViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil) {
//Create the fetch request first
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Here is the entity whose contents we want to read
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:[self managedObjectContext]];
NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:ageSort,firstNameSort, nil];
fetchRequest.sortDescriptors = sortDescriptors;
//Tell the request that we want to read the contents of Person entity
[fetchRequest setEntity:entity];
self.personsFRC = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
self.personsFRC.delegate = self;
NSError *fetchingError = nil;
if ([self.personsFRC performFetch:&fetchingError]) {
NSLog(@"Successfully fetched.");
}else{
NSLog(@"Failed to fetch.");
}
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"Persons";
self.tableViewPersons = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableViewPersons.delegate = self;
self.tableViewPersons.dataSource = self;
[self.view addSubview:self.tableViewPersons];
self.barButtonAddPerson = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewPerson:)];
[self.navigationItem setLeftBarButtonItem:[self editButtonItem] animated:NO];
[self.navigationItem setRightBarButtonItem:self.barButtonAddPerson animated:NO];
}
- (void)addNewPerson:(id)paramSender{
AddPersonViewController *controller = [[AddPersonViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
id<NSFetchedResultsSectionInfo> sectionInfo = [self.personsFRC.sections objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
static NSString *PersonTableViewCell = @"PersonTableViewCell";
result = [tableView dequeueReusableCellWithIdentifier:PersonTableViewCell];
if (result == nil) {
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PersonTableViewCell];
result.selectionStyle = UITableViewCellSelectionStyleNone;
}
Person *person = [self.personsFRC objectAtIndexPath:indexPath];
result.textLabel.text = [person.firstName stringByAppendingFormat:@".%@",person.lastName];
result.detailTextLabel.text = [NSString stringWithFormat:@"Age:%lu",(unsigned long)[person.age unsignedIntegerValue]];
return result;
}
-(NSManagedObjectContext *)managedObjectContext{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
return managedObjectContext;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
[self.tableViewPersons reloadData];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
Person *personToDelete = [self.personsFRC objectAtIndexPath:indexPath];
/*VERY IMPORTANT: we need to make sure we are not reloading the table view while deleting the managed object*/
self.personsFRC.delegate = self;
[[self managedObjectContext] deleteObject:personToDelete];
if ([personToDelete isDeleted]) {
NSError *savingError = nil;
if ([[self managedObjectContext] save:&savingError]) {
NSError *fetchingError = nil;
if ([self.personsFRC performFetch:&fetchingError]) {
NSLog(@"Successfully fetched.");
NSArray *rowsToDelegate = [[NSArray alloc] initWithObjects:indexPath, nil];
[_tableViewPersons deleteRowsAtIndexPaths:rowsToDelegate withRowAnimation:UITableViewRowAnimationAutomatic];
}else{
NSLog(@"Failed to fetch with error = %@",fetchingError);
}
}else{
NSLog(@"Failed to save the context with error = %@",savingError);
}
}
self.personsFRC.delegate = self;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing) {
[self.navigationItem setRightBarButtonItem:nil animated:YES];
}else{
[self.navigationItem setRightBarButtonItem:self.barButtonAddPerson animated:YES];
}
[self.tableViewPersons setEditing:editing animated:YES];
}
@end
AddPersonViewController.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AddPersonViewController : UIViewController
@property(nonatomic,strong)UITextField *textFieldFirstName;
@property(nonatomic,strong)UITextField *textFieldLastName;
@property(nonatomic,strong)UITextField *textFieldAge;
@property(nonatomic,strong)UIBarButtonItem *barButtonAdd;
@end
AddPersonViewController.m
#import "AddPersonViewController.h"
#import "AppDelegate.h"
#import "Person.h"
@interface AddPersonViewController ()
@end
@implementation AddPersonViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"New Person";
CGRect textFieldRect = CGRectMake(20.0f, 80.0f, self.view.bounds.size.width - 40.0f, 31.0f);
self.textFieldFirstName = [[UITextField alloc] initWithFrame:textFieldRect];
self.textFieldFirstName.placeholder = @"First Name";
self.textFieldFirstName.borderStyle = UITextBorderStyleRoundedRect;
self.textFieldFirstName.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.textFieldFirstName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.textFieldFirstName];
textFieldRect.origin.y += 37.0f;
self.textFieldLastName = [[UITextField alloc] initWithFrame:textFieldRect];
self.textFieldLastName.placeholder = @"Last Name";
self.textFieldLastName.borderStyle = UITextBorderStyleRoundedRect;
self.textFieldLastName.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.textFieldLastName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.textFieldLastName];
textFieldRect.origin.y += 37.0f;
self.textFieldAge = [[UITextField alloc] initWithFrame:textFieldRect];
self.textFieldAge.placeholder = @"Age";
self.textFieldAge.borderStyle = UITextBorderStyleRoundedRect;
self.textFieldAge.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.textFieldAge.keyboardType = UIKeyboardTypeNumberPad;
self.textFieldAge.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.textFieldAge];
self.barButtonAdd = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(createNewPerson:)];
[self.navigationItem setRightBarButtonItem:self.barButtonAdd animated:NO];
}
-(void)createNewPerson:(id)paramSender{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
if (newPerson != nil) {
newPerson.firstName = self.textFieldFirstName.text;
newPerson.lastName = self.textFieldLastName.text;
newPerson.age = [NSNumber numberWithInteger:[self.textFieldAge.text integerValue]];
NSError *savingError = nil;
if ([managedObjectContext save:&savingError]) {
[self.navigationController popViewControllerAnimated:YES];
}else{
NSLog(@"Failed to save the managed object context.");
}
}else{
NSLog(@"Failed to create the new person object.");
}
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self.textFieldFirstName becomeFirstResponder];
}
@end
7.运行结果: