-3

below is not working throwing an error , please help how to write a code for fetching data from Users entity.

attached screenenter image description here

Srini
  • 5
  • 3

1 Answers1

1

Grabbing appDelegate object and context

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

Adding a record in Core Data

let user = NSEntityDescription.insertNewObject(forEntityName: "UsersClass", into: context) as! UsersClass
user.userName = "Rajan"
appDelegate.saveContext()

Fetching

let fetchRequest:NSFetchRequest<UsersClass> = UsersClass.fetchRequest()

And then execute this request

do {
    let searchResults = try context.fetch(fetchRequest)
    for trans in searchResults {
        print(trans.username!)
    }
}
catch {
    //Handle error
}

UsersClass+CoreDataProperties.swift

import Foundation
import CoreData

extension UsersClass {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<UsersClass> {
        return NSFetchRequest<UsersClass>(entityName: "UsersClass");
    }

    @NSManaged public var userName: String?

}

Here is the Sample which I made.

Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98
  • *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: is not a valid NSFetchRequest.' *** First throw call stack: ( 0 CoreFoundation 0x00000001105e534b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010d51121e objc_exception_throw + 48 2 CoreData 0x000000010d9d4f6c -[NSManagedObjectContext executeFetchRequest:error:] + 4972 3 libswiftCoreData.dylib 0x000000010fb37e78 – Srini Oct 20 '16 at 18:53
  • At least add some record into it then it will fetch . Also show your managed object class i.e. Usersclass – Rajan Maheshwari Oct 20 '16 at 19:04
  • can you please share code for creating and fetching data....i am new to swift iOS – Srini Oct 21 '16 at 18:41
  • @Srini Did it helped you – Rajan Maheshwari Oct 22 '16 at 13:27
  • Well it helped me a treat. I don't know how many issues you had in your code but you at least needed to change NSFetchRequestResult with the name of your custom class – Ben Sullivan Dec 20 '16 at 12:46