在coreData async fetch中抓取数据

时间:2017-04-28 08:23:56

标签: ios core-data swift3

脚本在VC中我通过导航项目上的左键调用。

问题:

你能帮助我解释一下原因:如果我使用var productToCheck = Product() func工作填充数组,但我得到了Failed to call designated initializer on NSManagedObject class消息。相反,如果我应用var productToCheck = NSEntityDescription.insertNewObject(forEntityName: self.kProductEntityName, into: managedContext) as! Product 错误消失但VC出现时,在控制台上第一次显示产品的名称,但如果我在根VC和此VC之间来回,则在控制台上显示比产品名称更“未知”。

  • 异步提取我做错了吗?
  • 我是否在错误的空间中调用脚本?
  • 如果我将“问题”脚本移到func之外,它就永远不会评估
提前

thanx

// MARK: - async fetch request 1
var asyncFetchRequest: NSAsynchronousFetchRequest<Product>!
var asyncProductsArray : [NSManagedObject] = []

//MARK: - CoreData properties
var managedContext: NSManagedObjectContext!
let kProductEntityName = "Product"


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)


    makeAsyncFetch()


    //end viewWillAppear
}





func makeAsyncFetch() {


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


    // MARK: - async fetch request 2
    let productFetch = NSFetchRequest<Product>(entityName: kProductEntityName)

    asyncFetchRequest = NSAsynchronousFetchRequest<Product>(fetchRequest: productFetch) {
        [unowned self] (result: NSAsynchronousFetchResult) in
        guard let AllProductResult = result.finalResult else {
            return
        }
        self.asyncProductsArray = AllProductResult


        //********************* issue start **************************
        for singleProduct in self.asyncProductsArray {
            //thisbelow causes "Failed to call designated initializer on NSManagedObject class" message, but no data repeated in console
            //var productToCheck = Product()
            //this below silcences "Failed to call designated initializer on NSManagedObject class" message but causes "repeating" issue
            //            var productToCheck = NSEntityDescription.insertNewObject(forEntityName: self.kProductEntityName, into: managedContext) as! Product
            productToCheck = singleProduct as! Product
            //since the second time  this VC appears, "name" printed but also "unknown", each time once more than before
            print(productToCheck.name ?? "unknown")

        }
        //********************* issue ends **************************


    }
    // MARK: - async fetch request 3
    do {
        try managedContext.execute(asyncFetchRequest)
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

}

UPADTE

这是我用来添加测试实体的脚本

 //MARK: - reading csv

    //I read and clear the rows
    var data = readDataFromCSV(fileName: kCSVFileName, fileType: kCSVFileExtension)
    data = cleanRows(file: data!)
    let csvRows = csv(data: data!)

    //with this I make more cler wich index I'm using
    enum columnsProd : Int {

        case productId = 0
        case name = 1
        case category = 2
        case priceForCustomer = 3
        case priceForRetail = 4
        case quantity = 5
        case total = 6

    }

    //with this FOR loop below, I can have an index number and the ENTIRE element at that index, in this case is another array I can search in

    //I use dropFirst() in order to skip the first (n°) rows
    for (_/*index*/, element) in csvRows.dropFirst(2).enumerated() {

        //here I skip all the result that match the if:
        if element[columnsProd.productId.rawValue] != "" && !element[columnsProd.name.rawValue].contains("ORDINE SEPARATO") && !element[columnsProd.name.rawValue].contains("Gift Card") {

            var myFutureEntityInstance = myFutureEntity()

            var productIdentification = element[columnsProd.productId.rawValue]
            if productIdentification == "" {productIdentification = "unknown"; }

            var nameFromSingleRow = element[columnsProd.name.rawValue]
            if nameFromSingleRow == "" {nameFromSingleRow = "unknown"}

            var elementCAtegory = element[columnsProd.category.rawValue] //was a date for differnt class
            if elementCAtegory == "" {elementCAtegory = "unknown"}

            var thePriceCustomer = element[columnsProd.priceForCustomer.rawValue]
            if thePriceCustomer == "" {thePriceCustomer = "unknown"}

            var thePriceRetailer = element[columnsProd.priceForRetail.rawValue]
            if thePriceRetailer == "" {thePriceRetailer = "unknown"}

            myFutureEntityInstance.productName = nameFromSingleRow
            myFutureEntityInstance.productProdId = productIdentification
            myFutureEntityInstance.productCategory = elementCAtegory
            myFutureEntityInstance.productPriceCustomer = thePriceCustomer
            myFutureEntityInstance.productPriceRetailer = thePriceRetailer

            //here for avoid duplicates with same name
            self.productNameArray.append(nameFromSingleRow)

            //                here only for a test in wich I
            //                    if nameFromSingleRow == "Item Name" {
            //                        addTheItemToCoreData(futureEntity: myFutureEntityInstance)
            //                        print("added")
            //                    }


            //I fill an array with struct tha has the same structure of the future Entity
            self.asyncTempItemArray.append(myFutureEntityInstance)

        }



    }

func起诉添加项目

func addTheItemToCoreData(futureEntity : myFutureEntity) {
    //this func should be used to update the internal entitylist where only if a item is not present will be put to be shown in the list, tha0ts why each item is by default not present in collection

    //CoreData : appDelegte + managedContext
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
    let managedContext = appDelegate.persistentContainer.viewContext


    let entity = NSEntityDescription.entity(forEntityName: self.kItemEntityName, in: managedContext)!

    let itemToAdd = Item(entity: entity, insertInto: managedContext)
    itemToAdd.product_id = futureEntity.itemProdId
    itemToAdd.category = futureEntity.itemCategory
    itemToAdd.name = futureEntity.itemName
    itemToAdd.inMyCollection = false
    itemToAdd.inWishlist = false
    //        itemToAdd.priceCustomer = Double(futureEntity.itemPriceCustomer!)!
    //        itemToAdd.priceRecommended = Double(futureEntity.itemPriceRetailer!)!

    do {
        try managedContext.save()
    } catch let error as NSError {
        print("could not save. \(error), \(error.userInfo)")
    }

}

0 个答案:

没有答案