IOS: Define managed object contextcore data storage in appdelegate: Core dataiphone: Core Data: Where doe

Source: Internet
Author: User
Tags file url

I have made many summary about core data.

Core Data-This article introduces some core data architectures and basic implementations;

Data storage in iPhone development: Core Data ---- This article introducesExample of storing four textfields. Obtain the managed object context from appdelegate and perform access to it;

IPhone: Core Data: Where does a managed object context come from? ---- This article describes how to create a managed object context

 

In xcode (4.4 & 4.5), when you create a project, select empty application, and there is a core data option, it automatically runs the managed object context required for core data in appdelegate:

Appdelegate. h

 #import  
   
    @ interface  appdelegate: uiresponder 
    
     @ 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 didfinishlaunchingwitexceptions :( 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 shocould 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 changes 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 previusly 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 shocould 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 shoshould 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 defamanager manager] removeitematurl: storeurl error: nil] * specify Ming 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 ents directory //  Returns the URL to the application's documents ents directory. -(Nsurl * ) Applicationdocumentsdirectory {  Return [[Nsfilemanager defaultmanager] urlsfordirectory: nsdocumentdirectory indomains: nsuserdomainmask] lastobject];}  @ End 

You only need to call the managed object context to operate on the object. Besides, savecontext and applicationdocumentsdirectory can be saved and obtained.

 

Of course, you can configure core data in appdelegate based on the above method. Remember to reference the library when you add it and add it in. PCH.

# Import<Coredata/coredata. h>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.