2012年10月16日 星期二

CoreData核心數據的基本概念和實例方法(2) TableView的展現

CoreData核心數據的基本概念和實例方法(2)
TableView的展現

.h

#import <UIKit/UIKit.h>


@interface CBTBViewController : UITableViewController

@property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;

@property (strong) NSArray * CBArray; 
@property (strong) NSArray * CBImages;

@end


.m
#import <CoreData/CoreData.h>

#import "CBTBViewController.h"

#import "AppDelegate.h"

#import "CrowButterflies.h" //載入資料庫欄位

#import "CBViewController.h"



@interface CBTBViewController ()

@end

NSArray * CBArray;
NSArray * CBImages;

@implementation CBTBViewController

@synthesize managedObjectContext;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    CBArray = [[NSArray alloc] initWithObjects:@"斯氏紫斑蝶",@"端紫斑蝶",@"圓翅紫斑蝶",@"小紫斑蝶",@"大白斑蝶",@"黑脈樺斑蝶",@"樺斑蝶",@"淡紋青斑蝶",@"小紋青斑蝶",@"姬小青斑蝶",@"大青斑蝶",@"小青斑蝶", @"琉球青斑蝶",nil];
    CBImages = [[NSArray alloc] initWithObjects:@"crow01-icon.png",@"crow02-icon.png",@"crow03-icon.png",@"crow04-icon.png",@"crow05-icon.png",@"crow06-icon.png",@"crow07-icon.png",@"crow08-icon.png",@"crow09-icon.png",@"crow10-icon.png",@"crow11-icon.png",@"crow12-icon.png",@"crow13-icon.png", nil];

    // 載入 core data
    
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
        NSLog(@"After managedObjectContext: %@"managedObjectContext);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"CrowButterflies" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error;
    

//    NSLog(@"NSPredicate => %@", areaFilter);
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"crow_name != %@", @""];
    [fetchRequest setPredicate:predicate];

    
    CBArray = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
//    NSLog(@"%@", CBArray);
    
    // 結束 core data
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

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

    // Return the number of rows in the section.
//    return 0;
     return [CBArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    CrowButterflies *c = [CBArray objectAtIndex:indexPath.row];
    cell.textLabel.text = c.crow_name;
    cell.detailTextLabel.text = c.crow_S_name;
//    cell.imageView.image = (NSString *) [CBArray objectAtIndex:indexPath.row];
    
    cell.imageView.image = [UIImage imageNamed: (NSString *) [CBImages objectAtIndex:indexPath.row]];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"prepareForSegue");
    
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    CrowButterflies *p = [CBArray objectAtIndex:path.row];
    CBViewController *vc = [segue destinationViewController];
    vc.crowbutter = p;
}

@end










CoreData核心數據的基本概念和實例方法(1)



核心數據的基本概念和實例方法

建立專案時,勾選「Use Core Data」,AppDelegate.h,Xcode會自動宣告變數及方法在Class裡。
CoreData最重要的三個物件:
NSManagedObjectModel:資料庫的架構,包含資料表上各個欄位的屬性以及定義。
NSPersistentStoreCoordinator:此為資料庫連結,設定資料庫「名稱」、「位置」,及把資料更新到資料庫上都是使用coordinator.
NSManagedObjectContext:資料庫的內容,要取值、新增、刪除物件時,都是用到他的方法。

類別
用途 
方法 
NSManagedObject 
物件對象
管理屬性 
-entity
-valueForKey:
-setValue: forKey:
NSManagedObjectContext
資料庫內容
取得與儲存
-executeFetchRequest: error:
-save
NSManagedObjectModel
資料庫架構 
-entities
-fetchRequestTemplateForName:
-setFetchRequestTemplate: forName:
NSFetchRequest 
請求數據
-setEntity:
-setPredicate:
-setFetchBatchSize: 
NSPersistentStoreCoordinator 
儲存資料 
-addPersistentStoreWithType: configuration: URL: options: error:
-persistentStoreForURL: 
NSPredicate 
確定查詢條件 
+predicateWithFormat:
-evaluateWithObject: 


儲存資料到資料庫的方法- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{}
資料庫的儲存方式:
1.XML, XML具可讀性
2.SQLite, SQLite用於儲存大量資料時可節省空間
3.二進位或者是儲存於記憶體.可以依照自己的需求來決定, 二進位的存取非常快速但會使用大量記憶體所以不適用於操作大筆資料量


AppDelegate.h
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;  //資料庫內容取得與儲存
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;  //資料庫架構 
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;  //儲存資料

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

=============================================================
AppDelegate.m
#import "AppDelegate.h"

#import "MainViewController.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    MainViewController *controller = (MainViewController *)self.window.rootViewController;
    controller.managedObjectContext = self.managedObjectContext;
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext    //資料庫內容
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];   //儲存資料
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel  //資料庫架構
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coredata" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator  //檢查app若沒有資料庫,就把coredata.sqlite塞給他。
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"coredata.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory     //返回程式目錄
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end


























Tab Bar Icon

Tab Bar Icon的圖檔,png外,背景也要去掉,才可以使用。