CountForFetchRequest in Swift 2.0

I am trying to use the countForFetchRequest method in the context of a managed entity in Swift 2.0.

I note that the error handling for executeFetchRequest been changed to the new do-try-catch syntax:

 func executeFetchRequest(_ request: NSFetchRequest) throws -> [AnyObject] 

but the countForFetchRequest method still uses the obsolete error pointer:

 func countForFetchRequest(_ request: NSFetchRequest, error error: NSErrorPointer) -> Int 

... and it's a little difficult for me to understand how to use this in Swift 2.0.

If I do the same as pre-Swift 2.0:

 let error: NSError? = nil let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error) 

I get errors saying to remove & , but if I remove this, I get another error saying that NSError cannot be converted to NSErrorPointer .

Any help would be appreciated on how to do this.

+8
swift swift2 core-data nsfetchrequest
source share
2 answers

Your code is almost correct, but error must be variable in order to be passed as inout-argument with & :

 var error: NSError? = nil let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error) 

Update:. According to Swift 3, countForFetchRequest throws an error:

 do { let count = try managedObjectContext.context.count(for:fetchRequest) return count } catch let error as NSError { print("Error: \(error.localizedDescription)") return 0 } 
+25
source share

You need to do the following:

 let error = NSErrorPointer() let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error) print("Count \(fetchResults)") 

This is the code for Swift 2.0

0
source share

All Articles