Harry Harry - 1 year ago 81
Swift Question

Obtaining an array of objects from fetch request

I have an object called Projects that I save to core data. I then add multiple projects to core data. I want to retrieve those objects as an array from core data. The following code gets this error:

-[NSAsynchronousFetchResult mutableCopyWithZone:]: unrecognized selector sent to instance

var uploadPhotos : NSMutableArray? = []

var activeProject : String!

override func viewDidLoad() {

projectPicker.dataSource = self
projectPicker.delegate = self

isInSegmentPhoto = true

//let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Project")
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Project.fetchRequest()
let entityDescription = NSEntityDescription.entity(forEntityName: "Project", in: sharedDelegate.managedObjectContext)

fetchRequest.entity = entityDescription

do {
let result = try self.sharedDelegate.managedObjectContext.fetch(fetchRequest)

projects = result as! [Project]

} catch {
let fetchError = error as NSError


When I run the program it prints out the list of projects, but crashes on the first line of the do-catch.

Answer Source

Please, please use Swift native types, NSMutableArray has no type information.

var projects = [Project]()
projects = try defaultManagedObjectContext().execute(fetchRequest) as! [Project]

Since the fetch request is clearly a Project request you can safely unwrap the result.

mutableCopy() causes the error, because NSFetchRequestResult(the umbrella protocol of all possible result types) does not respond to that method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download