我正在尝试获取包含可转换类型TransType的对象CoreDataTypeA。我想获得与我传入NSPredicate的可转换类型相匹配的对象。当我返回下面的代码时,我总是得到0。
let predicate = NSPredicate(format: "TransType == %@", transType)
let fetchRequest : NSFetchRequest<CoreDataTypeA> = NSFetchRequest(entityName: "CoreDataTypeA")
fetchRequest.fetchLimit = 1
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
fetchRequest.predicate = predicate
do {
let requestReturn = try self.managedObjectContext.fetch(fetchRequest)
guard requestReturn.count != 1 else {
return 0.0 // Always returns THIS !!!!
}
let fetchedObj = requestReturn[0]
print("object Value: \(fetchedObj.value)")
return fetchedObj.objValue
} catch {
print("Error, not found!")
return 0.0
}
编辑:更改代码以删除guard语句以使其更容易:
let predicate = NSPredicate(format: "TransType == %@", transType)
let fetchRequest : NSFetchRequest<CoreDataTypeA> = NSFetchRequest(entityName: "CoreDataTypeA")
fetchRequest.fetchLimit = 1
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
fetchRequest.predicate = predicate
do {
let requestReturn = try self.managedObjectContext.fetch(fetchRequest)
if(requestReturn.count != 0) {
let fetchedObj = requestReturn[0]
print("object Value: \(fetchedObj.value)")
return fetchedObj.objValue
} else {
return 0.0 // STILL RETURNS HERE
}
} catch {
print("Error, not found!")
return 0.0
}