Reputation: 71
I write code
var fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "Doctor")
fetchRequest.predicate = NSPredicate(format: "id != nil")
let sortDescriptors: [NSSortDescriptor] = [(NSSortDescriptor.init(key: "distance", ascending: true)), (NSSortDescriptor.init(key: "lastname", ascending: true))]
fetchRequest.sortDescriptors = sortDescriptors
var error: NSError? = nil
// show error Value of type 'NSFetchRequest' has no member 'performFetch'
var fetchSuccessful: Bool = fetchRequest.performFetch(error)
Upvotes: 0
Views: 866
Reputation: 63369
What you're looking for is executeFetchRequest(_:)
which throws
rather than using taking an NSError
param.
If the last non-block parameter of an Objective-C method is of type NSError **, Swift replaces it with the throws keyword, to indicate that the method can throw an error. If the Objective-C method’s error parameter is also its first parameter, Swift attempts to simplify the method name further, by removing the “WithError” or “AndReturnError” suffix, if present, from the first part of the selector. If another method is declared with the resulting selector, the method name is not changed. - Using Swift with Cocoa and Objective-C (Swift 2.2) - Error Handling
Upvotes: 0
Reputation: 532
@Magdalena Dziesińska: In your code...
var fetchSuccessful: Bool = fetchRequest.performFetch(error)
"performFetch" does not exist. To handle the error (error handling) place it within a 'do-try-catch statement' e.g. after your code...
var fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "Doctor")
fetchRequest.predicate = NSPredicate(format: "id != nil")
let sortDescriptors: [NSSortDescriptor] = [(NSSortDescriptor.init(key: "distance", ascending: true)), (NSSortDescriptor.init(key: "lastname", ascending: true))] fetchRequest.sortDescriptors = sortDescriptors
Use the following do-try-catch statement to catch any errors and get the fetch request.
do {
let results = try context.executeFetchRequest(request)
} catch {
print("requesting error")
}
nb: request is where you place your "fetchRequest"
Upvotes: 1
Reputation: 6114
You can not perform fetch request without context. If you have NSManagedObjectContext
instance, you may use it executeFetchRequest(_:)
method with your fetch request. More, if you have NSFetchedResultsController
instance, initialized by your fetch request, you can use performFetch()
method of this controller. You absolutely need to read more documentation of CoreData https://developer.apple.com/library/watchos/documentation/Cocoa/Conceptual/CoreData/index.html
Upvotes: 0