Search code examples
swiftuitableviewcore-dataiphonecoredatarecipes

Core data is causing the iPhone crash


I don't have a problem in saving the data onto the Core Data. my problem is in that vc that I'm supposed to fetch the data.

CoreData

@objc(ItemInCard)
public class ItemInCard: NSManagedObject {

}

FETCH

let fetchRequest : NSFetchRequest<ItemInCard> = ItemInCard.fetchRequest()
    do
    {
        let itemIncard = try  PersistanceService.context.fetch(fetchRequest)
        self.item = itemIncard
        self.Tableview.reloadData()
    }
    catch
    {

    }

table view

var item = [ItemInCard]()
    //MARK: - Table view
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print("=======")
    print(item)
    return item.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingCardCell") as? ShppingCellCustomTableViewCell


    cell!.textLabel?.text = item[indexPath.row].productTitleCore

    self.Tableview.reloadData()
    return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 180
}

as long as that vc is open in the app it prints the core data(I added the print to check What is going on

it keeps printing the core data below

[<ItemInCard: 0x281a4efd0> (entity: ItemInCard; id: 0x87c125f9e2c25dff <x-coredata://139AE9B3-30B6-4857-8313-456481AF833C/ItemInCard/p1> ; data: {
    paymentTypeCore = "\U0648\U0627\U0631\U064a\U0632\U064a";
    priceCore = 10000;
    priceTypeCore = "\U0639\U0627\U062f\U06cc-test";
    productTitleCore = "\U062c\U0648 \U0627\U06a9\U0631\U0627\U06cc\U0646 \U0628\U0646\U062f \U0627\U0645\U0627\U0645 \U062a\U062d\U0648\U06cc\U0644 \U0645\U0647\U0631\U

but I only have one data in the app. also the table is not populated too


Solution

  • Remove the call to reloadData out of your cellForRowAt method. cellForRowAt is called when the app needs to reload the tableView. In effect your are telling it to begin the reload after each cell is created so you never get past the the first cell. This explains why you only see one item.