Search code examples
iosiphonejsoncore-dataios7

How to add Core Data to my project and store the data getting from JSON service


i am doing in appDelegate.h like this

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

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

and implementinig all these things in appDelegate.m


Solution

  • That's a pretty big question to handle, but typically you'd add something like this (if you're using UIManagedDocument) to your appdelegate.m's - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
                                                     inDomains:NSUserDomainMask] firstObject];
    NSString *documentName = @"YOUR_DATABASE_NAME";
    NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
    self.document = [[UIManagedDocument alloc] initWithFileURL:url];
    
    BOOL fileExists = [fileManager fileExistsAtPath:[url path]];
    if (fileExists) {
        [self.document openWithCompletionHandler:^(BOOL success) {
            if (success) {
                self.context = self.document.managedObjectContext;
                // Post notification so others can gather the document and context
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
                                                                    object:self];
            }
            if (!success) NSLog(@"couldn't open file at %@", url);
        }];
    } else {
        [self.document saveToURL:url
                forSaveOperation:UIDocumentSaveForCreating
               completionHandler:^(BOOL success) {
                   if (success) {
                       self.context = self.document.managedObjectContext;
                       // Post notification so others can gather the document and context
                       [[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
                                                                           object:self];
                   }
                   if (!success) NSLog(@"couldn't open file at %@", url);
               }];
    }
    

    You should put @property (strong, nonatomic) UIManagedDocument *document; in your appdelegate's .h file so that other view controllers can get the document. In view controllers that need to contact the database in some way, add this:

    - (void)awakeFromNib
    {
        // Listen for UIManagedDocument so that we can get the database set up right
        // This only works in awakeFromNib (viewDidLoad is too late)
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(getUIManagedDocument:)
                                                     name:@"DatabaseReady"
                                                   object:nil];
    }
    

    Then, you'll need to add the getUIManagedDocument: method to your view controller:

    - (void)getUIManagedDocument:(NSNotification *)notification
    {
        self.document = [(OneWorldAppDelegate *)[[UIApplication sharedApplication] delegate] document];
        self.context = self.document.managedObjectContext;
    }
    

    Of course you'll need to add

    @property (strong, nonatomic) UIManagedDocument *document;
    @property (strong, nonatomic) NSManagedObjectContext *context;
    

    to your files. That's where self.context comes from.

    At that point, you are ready to start doing things with your database.

    IMPORTANT: Don't forget to #import your appdelegate's .h file in the view controller in which you'd like to access the appdelegate's @property document!

    As far as getting JSON data, I recommend that you work through a tutorial, like this one. It explains things quite clearly.

    Hope it helps!