来自核心数据的访问集

时间:2019-04-28 13:49:20

标签: ios swift

我需要访问Core Data中的数组。

保存到核心数据:

func savePalletScanToCoreData(exported: Bool){

            //as this is not main thred need function to return appDelegate
            let appDelegate = CoreDataHelper.returnDelegate()

            let context = appDelegate.persistentContainer.viewContext
            let movementScans = NSMutableSet()
            for (item) in self.pallets {
                let movementScan = MovementScanEntity(context: context)
                movementScan.locationId = item.locationId
                movementScan.palletId = item.palletId
                movementScan.palletType = item.palletType
                movementScan.timestamp = item.timestamp
                movementScans.add(movementScan)
            }
//            print(movementScans)

            let newPalletScan = NSEntityDescription.insertNewObject(forEntityName: "PalletScanEntity", into: context)
            newPalletScan.setValue(self.timestamp, forKey: "timestamp")
            newPalletScan.setValue(exported, forKey: "exported")
            newPalletScan.setValue(self.userId, forKey: "userId")
            newPalletScan.setValue(self.deliveryId, forKey: "deliveryId")
            newPalletScan.setValue(movementScans, forKey: "pallets")
            print (newPalletScan)


            do
            {
                try context.save()
                print("CoreData SAVED!")
            }
            catch
            {
                //TODO: process error
            }
        }

newPalletScan.setValue(movementScans, forKey: "pallets")保存数组。 要从Core数据读取它,我正在使用:

func readNotExportedPalletScansFromCoreData() -> [NSManagedObject] {
            let appDelegate = CoreDataHelper.returnDelegate()
            let context = appDelegate.persistentContainer.viewContext

            let allPalletScansFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PalletScanEntity")
            //filter only unexported items
            allPalletScansFetch.predicate = NSPredicate(format: "exported == %@", NSNumber(value: false))

            var allPalletScansNotExported: [NSManagedObject] = [NSManagedObject]()

            do {
                allPalletScansNotExported = try context.fetch(allPalletScansFetch) as! [NSManagedObject]
                //print all fetched deliveryId
                for data in allPalletScansNotExported {
                    print(data.value(forKey: "deliveryId") as! String)
                }

                return allPalletScansNotExported

            } catch {
                //TODO: process error
            }

            return allPalletScansNotExported

        }

可以毫无问题地升至“第一级”,但在为data.value(forKey: "pallets")准备一切时却出错 如何阅读这些子项?它必须是基本的,但找不到任何显示如何进行排序的教程。

0 个答案:

没有答案