NSPredicate在CoreData中不返回Int32

时间:2018-08-02 08:50:19

标签: macos core-data swift4 nspredicate

Int32的谓词不起作用。

我在Core数据中有一个实体,其中一个实体的属性为Int32(见下文)。

enter image description here

我已经通过提取验证了Core Data中存储的数据:

enter image description here

我想使用Int32的谓词来扫描核心数据实体并检查条目:

extension serialPortIO {

// ************************************************
// MARK: - Core Data - Search for Object using uuid
// ************************************************
func entityExists(moc: NSManagedObjectContext, ioKitDevice: UInt32) -> Bool {

    var result: Bool = false

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SerialPortENT")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "ioKitDevice", ascending: true)]
    //fetchRequest.predicate = NSPredicate(format: "ioKitDevice = %i", Int32(ioKitDevice))


    do {let fetchResults = try moc.fetch(fetchRequest) as! [SerialPortENT]
        if fetchResults.count == 0 { result = false } else { result = true }
    } catch {
        messageClass().aLog(message: "[\(ioKitDevice) :: Record search error]", .Error)
    }        
    return result
}

每当我运行结果总是错误的。

1 个答案:

答案 0 :(得分:0)

CorePreData中带有Int32的NSPredicate的工作代码(Swift 4)

enter image description here

// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: "Photos", in: appDelegate.managedObjectContext)

print(ISRecordThere(Entity: Entity, ID: 5)) // True or False

这是获取数据功能

func ISRecordThere(Entity :NSEntityDescription,ID:Int?) -> Bool
{
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
    fetchRequest.predicate = NSPredicate(format: "id == %i", ID!)

    // Configure Fetch Request
    fetchRequest.entity = Entity

    do{

        let Fetchedresult = try appDelegate.managedObjectContext.fetch(fetchRequest)

        if  Fetchedresult.count > 0
        {
            let result:NSManagedObject = Fetchedresult[0] as! NSManagedObject

            if result.value(forKey: "id") as? Int != ID
            {
                return false
            }
            else
            {
                return true
            }
        }
        else
        {
            return false
        }
    }
    catch
    {
        let fetchError = error as NSError
        print(fetchError)
    }
    return false
}