Ayon Saha Ayon Saha - 4 months ago 22
Swift Question

NSPredicate array for NSCompoundPredicate

Please Help me, i want to make a coredata get function in Swift 2.2 NSPredicate array for NSCompoundPredicate

public func loadData(entityName: String, filters: [String: String] = [:], dataFault: Bool = true) -> [NSManagedObject] {
var listItems: [NSManagedObject]?
let delegate = UIApplication.sharedApplication().delegate as? AppDelegate

if let context = delegate?.managedObjectContext {
let fetchRequist = NSFetchRequest(entityName: entityName)
if (filters.count > 0) {
var predicte: [NSPredicate]
for (key, value) in filters {
let p1:NSPredicate = NSPredicate(format: "%K == %@", key, value as NSObject)
predicte.appendContentsOf(p1)
}
fetchRequist.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicte)
}
fetchRequist.returnsObjectsAsFaults = dataFault
do{
let results = try context.executeFetchRequest(fetchRequist)
listItems = results as? [NSManagedObject]
}
catch let err {
print(err)
}

}
else{
print("context Error")
}
return listItems!

}


There show error on predicte.appendContentsOf(p1)

Answer

In your code, p1 is not a CollectionType, so you need to use append, not appendContentsOf:

                predicte.append(p1)

Also, you need to initialize your predicte appropriately:

            var predicte: [NSPredicate] = []