9

I'm noob with Core Data and I can't find the help I need on the Apple developer website.

I defined a fetch request in my .xcdatamodeld file but now I can't find how to use it? This is the definition of the fetch request : enter image description here

I supose that the fetch request starts with :

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Category")

But I don't know how to use a fetch request by name. (The project is written in Swift 3)

Community
  • 1
  • 1
Maxime
  • 1,332
  • 1
  • 15
  • 43

2 Answers2

18

Bharath's answer is for how to create and execute a fetch request in code. This is commonly how you'll do it. However, it's not actually the answer to your question. If you actually create a fetch request named "allCategories" in the core data model like that, this is how you use it:

let fetchRequest = self.managedObjectModel.fetchRequestTemplate(forName: "allCategories")

let fetchedObjects = self.managedObjectContext.execute(fetchRequest!)
The Cappy
  • 623
  • 4
  • 8
  • I don't think that there is anything wrong with this method. But it isn't well documented. I have only seen this mentioned once. – The Cappy Nov 12 '16 at 19:19
  • Reference to other answer should be deleted since said answer has also been deleted. Also, your code assumes that the managedObjectModel has already been defined in this class. Better answer here imho: https://stackoverflow.com/questions/41391310/access-fetchrequest-from-xcdatamodel-in-ios – Maxi Mus May 13 '20 at 00:13
-2

If you had created an entity Users and inside it, you have created username and password. The fetch request for this will be the below code:

let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)      
let context:NSManagedObjectContext = appDel.managedObjectContext     
let request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false    
request.predicate = NSPredicate(format: "username = %@ AND password = %@", username1.text!, password1.text!)   
let results:NSArray = try! context.executeFetchRequest(request)
Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39