Search code examples
iosswiftcore-datanspredicate

Predicate doesn't work at CoreData - Swift 4


Im trying to load Name with index 1, but it's not working (CollectionView is empty).

CoreData:

enter image description here

LoadData:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequestTag = NSFetchRequest<NSManagedObject>(entityName: "Tag")
let PreValue = 1
let predicate = NSPredicate(format: "index == %i", PreValue)
fetchRequestTag.predicate = predicate

do {
   tagItems = try managedContext.fetch(fetchRequestTag)
} catch let error as NSError {
   print("Could not fetch. \(error), \(error.userInfo)")
}

TagCollectionView.reloadData()
TagCollectionView.selectItem(at: NSIndexPath(item: 0, section: 0) as IndexPath, animated: false, scrollPosition: [])

for data in tagItems {
   print("\(data.value(forKey: "name") as! String as Any), \(NSKeyedUnarchiver.unarchiveObject(with: data.value(forKeyPath: "index") as! Data) as! Int)")
}

Solution

  • The attribute type and the predicate type don't match.

    Transformable as type for an index is nonsensical anyway. Set the attribute type to Int32, or if there are only 0 and 1 indexes even to Bool.