Andrey M.
Andrey M.

Reputation: 3079

Sorting NSManagedObject array

I have a code in my project that should work. Simply, I want to sort fetched results of request by date of creation as follows:

0        context =...
1        let fetchRequest = NSFetchRequest(entityName: CoreDataValues.EntityName)
2        do {
3            let results = try context?.executeFetchRequest(fetchRequest)
4            let sortDescriptor = NSSortDescriptor(key: CoreDataValues.CreationDateKey, ascending: true)

5            if let sortedObjects = (results as? NSArray)?.sortedArrayUsingDescriptors([sortDescriptor]) as? [NSManagedObject] {
6                searchTextObjects = sortedObjects
7                tableView.reloadData()
8            }

9        } catch let error as NSError {
10            print("Could not fetch \(error), \(error.userInfo)")
11        }

But on the 5 line i've got warning: "Cast from [AnyObject]? to unrelated type NSArray always fails".

Upvotes: 2

Views: 1221

Answers (1)

vadian
vadian

Reputation: 285092

Your code is a bit complicated.

The recommended way is to pass the sort descriptor along with the fetch request

   context =...
   let fetchRequest = NSFetchRequest(entityName: CoreDataValues.EntityName)
   let sortDescriptor = NSSortDescriptor(key: CoreDataValues.CreationDateKey, ascending: true)
   fetchRequest.sortDescriptors = [sortDescriptor]
   do {
        searchTextObjects = try context?.executeFetchRequest(fetchRequest)
        tableView.reloadData()

   } catch let error as NSError {
       print("Could not fetch \(error), \(error.userInfo)")
   }

Regarding your error:

executeFetchRequest returns [AnyObject] so you might cast the type to the proper type as soon as possible.

let results = try context.executeFetchRequest(fetchRequest) as! [NSManagedObject]

I recommend also to make context non-optional (like in the most recent Core Data template)

Upvotes: 7

Related Questions