iOS:在AppDelegate中定義managed object contextCore Dataiphone開發中的資料存放區:Core Dataiphone:Core Data:Where doe

來源:互聯網
上載者:User

關於core data 的,我之前已經做了好多小結

Core Data ---這篇介紹了core data的一些架構及基本實現;

iphone開發中的資料存放區:Core Data ----這篇介紹了儲存四個textField的例子。從appdelegate中拿到managed object context,然後對其進行存取操作;

iphone:Core Data:Where does a Managed Object Context Come From? ----這篇介紹了如何建立擷取managed object context

 

其實在xcode(4.4&4.5)中,在開始建立項目時選擇Empty Application,就有一個core data的選項,它會自動在AppDelegate中core data所需的managed object context等:

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"@implementation AppDelegate@synthesize managedObjectContext = _managedObjectContext;@synthesize managedObjectModel = _managedObjectModel;@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    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:@"zhyCoreDataSetupDemo" 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{    if (_persistentStoreCoordinator != nil) {        return _persistentStoreCoordinator;    }        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"zhyCoreDataSetupDemo.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

你只要調用managed object context即可對其操作。還有saveContext、applicationDocumentsDirectory可儲存和擷取目錄。

 

當然你也可以仿照上面的方法在AppDelegate就配置好core data的這些東西,記住自己加的時候要引用庫,及在.pch中加

#import <CoreData/CoreData.h>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.