IOS学习笔记(八)CoreData

RootViewController.h

 1 @interface RootViewController : UITableViewController<NSFetchedResultsControllerDelegate>

 2 {

 3     NSManagedObjectContext *managedObjectContext;//被管理对象上下文

 4     //使用Core Data的框架,大多数的功能都可以自动实现,因为我们有managed object context(管理对象的上下文,有时直接叫"Context")。managed object context就像是一个关卡,通过它可以访问框架底层的对象——这些对象的集合我们称之为"persistence stack"(数据持久栈)。 managed object context作为程序中对象和外部的数据存储的中转站。栈的底部是persistence object stores(持久化数据存储)

 5     NSFetchedResultsController *__fetchedResultsController;//fetchedResultsController

 6     //NSFetchedResultsController和UITableView集成起来处理数据具有强大的灵活性。一般来说,你会创建一个NSFetchedResultsController实例作为table view的成员变量。

 7     //我们知道表格视图有很多种形式, fetched results 控制器主要针对列表视图,这种视图是由很多section组成的,每个section又包含了很多row。我们只需要在使用时配置 NSFetchedResultsController对象:entity是什么,如何排序(必须配置),预筛选项(可选)。NSFetchedResultsController就会自动帮你处理好每个section都应该显示哪些数据。

 8     

 9     

10     UISearchBar *searchBar;//搜索

11     //NSFetchedResultsController *__search_fetchedResultsController;

12     NSMutableArray *searchResultArray;

13 }

14 

15 @property(nonatomic,strong)NSManagedObjectContext *managedObjectContext;

16 @property(nonatomic,strong)NSFetchedResultsController *fetchedResultsController;

17 //@property(nonatomic,strong)NSFetchedResultsController *search_fetchedResultsController;

18 @end

RootViewController.m

 1 - (id)initWithStyle:(UITableViewStyle)style

 2 {

 3     self = [super initWithStyle:style];

 4     if (self) {

 5         // Custom initialization

 6         id delegate = [[UIApplication sharedApplication] delegate];//设置代理为AppDelegate

 7         //在初始化函数中,我们看到通过获取delegate,再通过delegate调用方法managedObjectContext,这样就得到了这个NSManagedObjectContext对象,NSManagedObjectContext对象它会跟NSPersistentStoreCoordinator对象打交道,NSPersistentStoreCoordinator会去处理底层的存储方式。

 8         self.managedObjectContext = [delegate managedObjectContext];//得到被管理对象上下文

 9         

10 //        NSString *path = [[NSBundle mainBundle]pathForResource:@"backg" ofType:@"jpg"];

11 //        UIImage *backgroudImage =[UIImage imageWithContentsOfFile:path];

12 //        [self.view setBackgroundColor:[UIColor colorWithPatternImage:backgroudImage]];

13 

14     }

15     return self;

16 }
-(void)addButtonPushed:(UIBarButtonItem *)button

{

    AddStudentViewController *addStudentViewController = [[AddStudentViewController alloc]init];

    //从底部push view

    CATransition *animation = [CATransition animation];

    [animation setType:kCATransitionMoveIn];

    [animation setSubtype:kCATransitionFromTop];

    [animation setDuration:1.0f];

    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

    [self.navigationController pushViewController:addStudentViewController animated:NO];

    [self.navigationController.view.layer addAnimation:animation forKey:@"pushView"];

    [addStudentViewController release];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    if(tableView == self.tableView)

    {

        id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];

        //This protocol defines the interface for section objects vended by an instance of NSFetchedResultsController.

        //这个协议定义了由NSFetchedResultsController返回的section对象的接口

        return [sectionInfo numberOfObjects];//返回section对象中的对象数量

    }

}
 1 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

 2 {

 3     if (editingStyle == UITableViewCellEditingStyleDelete) {//删除操作

 4         // Delete the row from the data source

 5         NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];

 6         [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

 7         //通过fetchedResultsController在上下文中删除indexpath处的对象

 8         NSError *error;

 9         if(![context save:&error])

10         {

11             NSLog(@"Unresolved error %@, %@",error,[error userInfo]);

12             abort();

13         }

14     }   

15 

16     else if (editingStyle == UITableViewCellEditingStyleInsert) {

17         // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

18     }   

19 }
 1 #pragma mark - NSFetchedResultsControllerDelegate

 2 //NSFetchedResultsController代理方法 通常都用如下格式

 3 //如果你为fetched results控制器设置了代理,代理会收到从它的managed object context中传来改变通知。delegate会处理context中任何会影响结果集或者section的变化,results也做相应的更新。控制器会告诉delegate结果集改变了什么或者section变化了哪些。你只要覆写几个方法来更新table view就行。

 4 

 5 -(void)controllerWillChangeContent:(NSFetchedResultsController *)controller

 6 {

 7     [self.tableView beginUpdates];//在controllerWillChangeContent:方法中指定开始更新

 8 }

 9 -(void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type//更新section的方法

10 {

11     switch (type) {

12         case NSFetchedResultsChangeInsert:

13             [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];//插入section

14             break;

15         case NSFetchedResultsChangeDelete:

16             [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];//删除section

17             break;

18         default:

19             break;

20     }

21 }

22 -(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath//更新row的方法

23 {

24     //    enum {

25     //        NSFetchedResultsChangeInsert = 1,

26     //        NSFetchedResultsChangeDelete = 2,

27     //        NSFetchedResultsChangeMove = 3,

28     //        NSFetchedResultsChangeUpdate = 4

29     //    };NSFetchedResultsChangeType

30     UITableView *tableView = self.tableView;

31     switch (type) {

32         case NSFetchedResultsChangeInsert:

33             [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];//在newIndexPath处插入行

34             break;

35         case NSFetchedResultsChangeDelete:

36             [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];//在indexPath处删除行

37             break;

38         case NSFetchedResultsChangeUpdate:

39             [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];//更新行

40             break;

41         case NSFetchedResultsChangeMove://移动行

42             [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];//先删除旧的indexPath处的行

43             [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];//再插入到newIndexPath处

44             break;

45         default:

46             break;

47     }

48 }

49 -(void)controllerDidChangeContent:(NSFetchedResultsController *)controller

50 {

51     [self.tableView endUpdates];//在controllerDidChangeContent:方法中指定结束更新

52 }
 1 -(void)addStudent//利用被管理对象上下文添加学生

 2 {

 3     if([self.nameTextField.text length] == 0)

 4     {

 5         NSLog(@"here");

 6         UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误" message:@"姓名不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

 7         [alert show];

 8         return;

 9     }

10 

11     Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedObjectContext];//创建新的学生对象

12     student.name = self.nameTextField.text;//学生姓名

13     student.age = [[NSNumber alloc]initWithInt:[self.ageTextField.text intValue]];//学生年龄

14     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

15     [dateFormatter setDateFormat:@"yyyy-MM-dd"];

16     student.birthday = [dateFormatter dateFromString:self.birthdayTextField.text];//学生出生年月

17     

18     //照片 在document中生成一张png图片,把路径跑村在student.image中

19     if(currentImage != nil)

20     {

21         NSData *imageData = UIImagePNGRepresentation(currentImage);

22         NSString *homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

23         NSLog(@"homepath = %@",homePath);

24         NSString *fileName = [NSString stringWithFormat:@"%@%d",student.name,[student.age intValue]];

25         NSFileManager *fileManager = [NSFileManager defaultManager];

26         

27         NSString *path = [homePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",fileName]];

28         if([fileManager fileExistsAtPath:path])

29         {

30             fileName  = [fileName stringByAppendingFormat:@"1"];

31             path = [homePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",fileName]];

32         }

33         NSLog(@"path = %@",path);

34         NSError *err = nil;

35         [imageData writeToFile:path options:NSDataWritingAtomic error:&err];

36         if(err)

37         {

38             NSLog(@"error = %@",[err description]);

39         }

40         student.image = [NSString stringWithFormat:@"%@.png",fileName];

41     }

42     

43     //student.photo = [NSString stringWithFormat:@"%d",arc4random()%25];

44     NSError *error = nil;

45     if(![managedObjectContext save:&error])//把上下文中的操作保存到持久库中

46     {

47         NSLog(@"Unresolved error %@, %@",error,[error userInfo]);

48         abort();

49     }

50     [self.navigationController popViewControllerAnimated:YES];//从navigationController中出栈

51 }

你可能感兴趣的:(coredata)