Unable to fetch data from coredata in swift?

core data fetch request swift 4
core data not saving swift
core data update existing object swift
nsfetchrequest
nsmanagedobjectcontext
core data swift 5
core data fetch relationship predicate
core data get object by id swift

i am tryng to fetch the data from coredata. Coredata was implemented in Objective-c . i want to fetch the data in swift file. in project we are using both swift and objective -c .

this is logic i written to fetch the data in swift file.

 let context = appDelegate.persistentContainer.viewContext

let request = NSFetchRequest<NSFetchRequestResult>(entityName: ProjectList_table)
do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
               print(data.value(forKey: "username") as! String)
          }

        } catch {

            print("Failed")
        }

i am trying to use above code its throwing error. "Appdelegate has no member persistentContainer"

this is my objective-c files for coredata

CoreDataController .h file
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataController : NSObject

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

- (void)saveContext;

@end

CoreDataController .m file

#import "CoreDataController.h"

@implementation CoreDataController

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

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

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_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:@"expenseDetails" 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:@"UserDetails.sqlite"];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSURL* storeURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingString:@"/expenseDetails.sqlite"] isDirectory:NO];

    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;
}

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


- (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();
        }
    }
}



@end

can someone tell me how to fetch the data in swift

first you have to initialize objective class in your swift file and call managed object context.

Example:

 let contextRefObj = CoreDataController()

  let context =   contextRefObj.managedObjectContext;

try this way , let me know if you face any issues still.

Core Data Programming Guide: Troubleshooting Core Data, Core Data will try to realize the faulted managed object but will fail to do so because the object Without potentially fetching large numbers of objects, possibly without reason, Swift. let entityInstance = NSEntityDescription. Core Data tries to keep its memory footprint as low as possible and one of the strategies it uses to accomplish this is faulting. When we fetched the records for the Person entity a moment ago, Core Data executed the fetch request, but it didn't fully initialize the managed objects representing the fetched records.

This should solve your problem :-

let context = appDelegate.managedObjectContext

executeFetchRequest:error:, Returns an array of objects that meet the criteria specified by a given fetch request. SDKs. iOS 3.0+; macOS 10.4+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ Core Data. On This Page. Declaration; Parameters; Return Value; Discussion; See with the throws keyword to indicate that it throws an error in cases of failure. Core Data Implementation . Click Show Project Navigator and select CoreData model file (ending with extension .xcdatamodelid) Click Add Entity option available at the bottom of Xcode Editor window. Then enter the name of the entity as Tasks. Click Add Attribute then enter name as desc and choose the type as String.

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

[https://github.com/Ashutos39/ContactBookDemo][1] if you have the doubt please check this project I have created you can get all fetch, insert to delete from core data concept.

What Is a Core Data Fault, Faulting is a concept that often confuses developer new to Core Data. Open NotesViewController.swift and navigate to the fetchNotes() method. persistent store that no longer exists, it tells you it is unable to fulfill the fault. When data is fetched from a persistent store, Core Data tries to be as efficient as possible in terms of memory usage. It only fetches the data the application asked for. Data that is not required is turned into a fault. The data is available, but Core Data hasn't fetched it from the persistent store to save memory and improve performance.

Reading and Updating Managed Objects With Core Data, [NSManagedObject] { result = records } } catch { print("Unable to fetch Core Data, we discuss it in detail in Mastering Core Data With Swift 3. Add new records to Core Data Fetch a set of records from Core Data Display the fetched records using a table view. You’ll also get a sense of what Core Data is doing behind the scenes, and how you can interact with the various moving pieces. Getting Started. Open Xcode and create a new iOS project based on the Single View App template.

How to access a Core Data managed object , If you followed my Core Data and SwiftUI set up instructions, you've already viewContext else { fatalError("Unable to read managed object context. for performing fetch requests using @FetchRequest – you only need it for  Deleting a record from a persistent store involves three steps: To show you how to delete a record, we delete an item record from the list record every time the application is run. If the list record has no item records left, we delete the list record itself.

Introduction to CoreData, Learn how to build Make School Notes in Swift 4 Finally, we'll be able to save notes and rest assured that they'll still be there later. Whenever the app launches, we want to use Core Data to retrieve and display the user's previously​  Core Data allows us to link entities together using relationships, and when we use @FetchRequest Core Data sends all that data back to us for use. However, this is one area where Core Data shows its age a little: to get relationships to work well we need to make a custom NSManagedObject subclass that providers wrappers that are more friendly to SwiftUI.

Comments
  • it's work in swift?
  • its not working in swift .
  • @vasuk Try this it's Working stackoverflow.com/a/51700569/10150796
  • in appdelegate i haven't declare anything .
  • Ohh Sorry I missed something in your code. Could you tell me from where you can easily access your CoreDataController file. You need to access "managedObjectContext" from this file
  • let context = appDelegate.persistentContainer.viewContext i tried its throwing error. "Appdelegate has no member persistentContainer"
  • first, confirm that your app is supporting ios 10.0 and above versions. And App delegate having this func lazy var persistentContainer: NSPersistentContainer = {}