//YJYAppDelegate.m
#import "YJYAppDelegate.h"
#import "YJYMasterViewController.h"
@implementation YJYAppDelegate
//@synthesize managedObjectContext = _managedObjectContext;的含義就是屬性managedObjectContext的存取方法是做用于_managedObjectContext這個變量的。
//managedObjectContext是屬性,而_managedObjectContext才是變量,我們最終操作的變量都是managedObjectContext。@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
//當由于其它方法打開應用程序(如URL指定或者連接),通知委托啟動完畢
- (BOOL)application:(UIApplication *)appl
@implementation YJYAppDelegate
//@synthesize managedObjectContext = _managedObjectContext;的含義就是屬性managedObjectContext的存取方法是做用于_managedObjectContext這個變量的。
//managedObjectContext是屬性,而_managedObjectContext才是變量,我們最終操作的變量都是managedObjectContext。
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
//當由于其它方法打開應用程序(如URL指定或者連接),通知委托啟動完畢
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"didFinishLaunchingWithOptions begin running()...");
// Override point for customization after application launch.
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
splitViewController.delegate = (id)navigationController.topViewController;
UINavigationController *masterNavigationController = splitViewController.viewControllers[0];
YJYMasterViewController *controller = (YJYMasterViewController *)masterNavigationController.topViewController;
controller.managedObjectContication didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"didFinishLaunchingWithOptions begin running()...");
// Override point for customization after application launch.
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
splitViewController.delegate = (id)navigationController.topViewController;
UINavigationController *masterNavigationController = splitViewController.viewControllers[0];
YJYMasterViewController *controller = (YJYMasterViewController *)masterNavigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
NSLog(@"didFinishLaunchingWithOptions() over...");
returnYES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{// 通知委托應用程序將進入非活動狀態,在此期間,應用程序不接收消息或事件,比如來電話了
NSLog(@"applicationWillResignActive() begin...over該方法沒內容");
// 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.
}
//這個方法定義的是當應用程序退到后臺時將執行的方法,按下home鍵執行(通知中心來調度)
//實現此方法的目的是將托管對象上下文存儲到數據存儲區,防止程序退出時有未保存的數據
- (void)applicationWillTerminate:(UIApplication *)application
{//當程序將要退出是被調用,通常是用來保存數據和一些退出前的清理工作。這個需要要設置
//applicationWillTerminate: 在程序結束前,Core Data會保存任何對其的更改
// Saves changes in the application's managed object context before the application terminates.
[selfsaveContext];
}
//相當與持久化方法
- (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
/*
先建立一個managedObjectModel,
然后根據 managedObjectModel 建立 persistentStoreCoordinator
然后根據 persistentStoreCoordinator 建立 managedObjectContext
然后是把managedObjectContext傳給真正要使用數據的 viewcontroller
*/
// 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
{//返回managedObjectContext對象
//自定義的managedObjectContext的getter, 它其實是真正在使用的時候的被操作對象
NSLog(@"managedObjectContext() begin...");
if (_managedObjectContext != nil) {//_managedObjectContext存在,直接返回
return_managedObjectContext;
}
//_managedObjectContext不存在,創建后返回
NSPersistentStoreCoordinator *coordinator = [selfpersistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContextalloc] init];//創建一個_managedObjectContext對象
[_managedObjectContextsetPersistentStoreCoordinator:coordinator];
//這里可以看到,“內容管理器”和“數據一致性存儲器”的關系,
//managedObjectContext需要得到這個“數據一致性存儲器”
}
NSLog(@"managedObjectContext() over...");
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
{//自定義的CoreData數據模板的getter,數據模板其實就是一個描述實體與實體的關系
//,類似于關系型數據庫的關系描述文件
NSLog(@"managedObjectModel() begin....");
if (_managedObjectModel != nil) {
return_managedObjectModel;
}
NSURL *modelURL = [[NSBundlemainBundle] URLForResource:@"YJY"withExtension:@"momd"];//這里的URLForResource:@"YJY" 的url名字(YJY)要和你建立datamodel時候取的名字是一樣的,至于怎么建datamodel很多教程講的很清楚,擴展名是momd
_managedObjectModel = [[NSManagedObjectModelalloc] initWithContentsOfURL:modelURL];
NSLog(@"managedObjectModel() over...");
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
{//自定義“數據一致性存儲器” persistentStoreCoordinator的getter
NSLog(@"persistentStoreCoordinator() begin...");
if (_persistentStoreCoordinator != nil) {
return_persistentStoreCoordinator;
}
//定義一個本地地址到NSURL,用來存儲那個SQLite文件
//這個地方的lich.sqlite名字沒有限制,就是一個數據庫文件的名字
NSURL *storeURL = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@"YJY.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];
//從這里可以看出,其實persistentStoreCoordinator需要的不過是一個
//存儲數據的位置,它是負責管理CoreData如何儲存數據的
if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:nilerror:&error]) {// Handle the 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();
}
NSLog(@"persistentStoreCoordinator() over...");
return_persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
//Documents目錄路徑,應用程序沙箱下的Documents目錄路徑
//返回該程序的檔案目錄,用來簡單使用
NSLog(@"applicationDocumentsDirectory() begin...over");
return [[[NSFileManagerdefaultManager] URLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask] lastObject];
}
@end
新聞熱點
疑難解答