Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9014871
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T03:37:01+00:00 2026-06-16T03:37:01+00:00

I have been trying like hell to figure out how to establish a connection

  • 0

I have been trying like hell to figure out how to establish a connection between my Core Data & my SQL database. The database isn’t pre-populated, but it will be used amongst many different users when it’s launched.

I have gone through the Core Data & iCloud classes provided by Stanford three times to no avail. I have also looked throughly into SQLite/SQL relational databases in iOS to no avail. The only other option I have is to come on here, post all the code I can, and pray that somebody will have an answer for me. So here it goes…

AppDelegate.m

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [self applicationDocumentsDirectory];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"shindy.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

- (NSURL *)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"shindy.sqlite"];

    return [NSURL fileURLWithPath:path];
}

HomeViewController.m

- (void)setupFetchedResultsController
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Shindy"];
    request.sortDescriptors = [NSArray arrayWithObjects:
                               [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES],
                               [NSSortDescriptor sortDescriptorWithKey:@"dateAndTime" ascending:YES],
                               [NSSortDescriptor sortDescriptorWithKey:@"photo" ascending:YES],
                               [NSSortDescriptor sortDescriptorWithKey:@"details" ascending:YES],
                               [NSSortDescriptor sortDescriptorWithKey:@"timePosted" ascending:YES],
                               [NSSortDescriptor sortDescriptorWithKey:@"location" ascending:YES],
                                                                                                    nil];

    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.shindyDatabase.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];

}

- (void)fetchShindyDataIntoDocument:(UIManagedDocument *)document
{
    dispatch_queue_t fetchQ = dispatch_queue_create("Shindy Fetcher", nil);
    dispatch_async(fetchQ, ^{
        NSArray *shindys = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
        NSLog(@"shindys = %@", shindys);
        [document.managedObjectContext performBlock:^{
            for (NSDictionary *shindyInfo in shindys) {
                [Shindy shindyWithShindyDBInfo:shindyInfo inManagedObjectContext:document.managedObjectContext];
                NSLog(@"fire");
            }
        }];
    });
}

- (void)useDocument
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"shindy.sqlite"];

    if (![[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil]) {
        [self.shindyDatabase saveToURL:self.shindyDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
            [self fetchShindyDataIntoDocument:self.shindyDatabase];
        }];
    } else if (self.shindyDatabase.documentState == UIDocumentStateClosed) {
            [self.shindyDatabase openWithCompletionHandler:^(BOOL success) {
        [self setupFetchedResultsController];
        }];
    } else if (self.shindyDatabase.documentState == UIDocumentStateNormal) {
        [self setupFetchedResultsController];
    }
}

- (void)setShindyDatabase:(UIManagedDocument *)shindyDatabase
{
    [self useDocument];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self fetchShindyDataIntoDocument:self.shindyDatabase];

    if (!self.shindyDatabase) {
        [self setShindyDatabase:self.shindyDatabase];
    }
}

Shindy+ShindyDB.m

+ (Shindy *)shindyWithShindyDBInfo:(NSDictionary *)shindyInfo
            inManagedObjectContext:(NSManagedObjectContext *)context
{
    Shindy *shindy = nil;

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Shindy"];

    NSSortDescriptor *dateAndTimeSort = [NSSortDescriptor sortDescriptorWithKey:@"dateAndTime" ascending:YES];
    NSSortDescriptor *detailsSort = [NSSortDescriptor sortDescriptorWithKey:@"details" ascending:YES];
    NSSortDescriptor *locationSort = [NSSortDescriptor sortDescriptorWithKey:@"location" ascending:YES];
    NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    NSSortDescriptor *photoSort = [NSSortDescriptor sortDescriptorWithKey:@"photo" ascending:YES];
    NSSortDescriptor *timePostedSort = [NSSortDescriptor sortDescriptorWithKey:@"timePosted" ascending:YES];
    // title
    request.sortDescriptors = [NSArray arrayWithObjects:dateAndTimeSort, detailsSort, locationSort, nameSort, photoSort, timePostedSort, nil];

    NSError *error = nil;
    NSArray *matches = [context executeFetchRequest:request error:&error];

    if (!matches || ([matches count] > 1)) {
        // handle error
    } else if ([matches count] == 0) {
        shindy = [NSEntityDescription insertNewObjectForEntityForName:@"Shindy" inManagedObjectContext:context];

        shindy.dateAndTime = [shindyInfo objectForKey:@"dateAndTime"];
        shindy.details = [shindyInfo objectForKey:@"details"];
        shindy.location = [shindyInfo objectForKey:@"location"];
        shindy.name = [shindyInfo objectForKey:@"name"];
        shindy.photo = [shindyInfo objectForKey:@"photo"];
        shindy.timePosted = [shindyInfo objectForKey:@"timePosted"];
        // title
        // Guestlist? The rest?
        // Use below for reference
        shindy.whoseShindy = [User userWithName:[shindyInfo objectForKey:@"whoseShindy"] inManagedObjectContext:context];
    } else {
        shindy = [matches lastObject];
    }

    shindy = [NSEntityDescription insertNewObjectForEntityForName:@"Shindy" inManagedObjectContext:context];
    shindy.dateAndTime = [shindyInfo objectForKey:@"dateAndTime"];
    shindy.details = [shindyInfo objectForKey:@"details"];
    shindy.location = [shindyInfo objectForKey:@"location"];
    shindy.name = [shindyInfo objectForKey:@"name"];
    shindy.photo = [shindyInfo objectForKey:@"photo"];
    shindy.timePosted = [shindyInfo objectForKey:@"timePosted"];

    return shindy;
}

AddShindyViewController.m

- (void)saveShindyToDatabase
{
    NSArray *shindys = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    [self.shindyDatabase.managedObjectContext performBlock:^{
        for (NSDictionary *shindyInfo in shindys) {
            [Shindy shindyWithShindyDBInfo:shindyInfo inManagedObjectContext:self.shindyDatabase.managedObjectContext];

            NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
            // url = [url URLByAppendingPathComponent:@"Default Shindy Database"];
            self.shindyDatabase = [[UIManagedDocument alloc] initWithFileURL:url];

            [self.shindyDatabase setValue:self.detailView.text forKey:@"details"];

            if (FBSession.activeSession.isOpen) {
                [[FBRequest requestForMe] startWithCompletionHandler:
                    ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                        if (!error) {
                            self.name = user.name;
                            self.photo.profileID = user.id;
                            self.username = user.username;
                        }
                    }];
            }
            [self.shindyDatabase setValue:self.name forKey:@"name"];
            [self.shindyDatabase setValue:self.photo forKey:@"photo"];
            [self.shindyDatabase setValue:self.username forKey:@"username"];
            // [Guest guestWithName:self.name username:self.username photo:self.photo inManagedObjectContext:self.shindyDatabase.managedObjectContext];
            [self.shindyDatabase setValue:self.locationManager.location forKey:@"location"];
            [self.shindyDatabase setValue:self.dateAndTimePicker.date forKey:@"dateAndTime"];
        }
    }];
}

I know what I’m asking for is a hell of a lot, but I have exhausted every single resource I have at my disposal. If anybody can even just point me in the right direction, I would be eternally grateful!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T03:37:02+00:00Added an answer on June 16, 2026 at 3:37 am

    If you plan to map an existing database with CoreData you will be unsuccessful.
    There’s infact no way you can map any database with CoreData.

    Core Data infact is a graph object management, with different storage option, and sqllite is just one of the possibility. At startup, if you choose sqllite as option, your application is going to create a database with a specific tables structure. If you try to connect to a database not created by CoreData framework you will get an error.

    What you can do is get rid of CoreData, and build your NSObject to act like entities. But then, you will have to implement all the logic to save, update, versioning, concurrency ecc… and it’s a long (and buggy) way, especially in a multi user environment.

    Otherwise, tell me if I misunderstood your question. Maybe, you can post an error stack trace.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been trying to figure this out a while. I would like to
I have been trying to figure out the logic of upgrading web applications. Like
I have been trying to convert sdot like this html_entity_decode(&sdot;); Any tips?
I have been trying to to figure out how to define a nested URL
I have been trying to figure out a Java RegEx for some while now
I have been trying to install ReviewBoard and all looks like it has gone
I have been trying to change the cursor style to look like a pointer
I have been trying for almost a week now to create an SQLite database
I have been trying to subclass the UINavigationController class for modifying things like background
I have been trying to find out if MSbuild can send an email to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.