简体   繁体   中英

custom fetch core data (swift)

My Data Model

在此处输入图片说明

Fetch func

func fetchAndSetResults2(){
    let dataController = DataController.sharedController
    let moc = dataController.managedObjectContext
    let request = NSFetchRequest(entityName: "Cart")
    let formatSort = NSSortDescriptor(key: "cartId", ascending: true)
    request.sortDescriptors = [formatSort] //[formatSort, nameSort]
    request.predicate = NSPredicate(format: "cartToUser.userId = %@", serverUserId)


    fetchedResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: "cartId", cacheName: nil)
    fetchedResultController.delegate = self

    do {
        try fetchedResultController.performFetch()  
    }
    catch {
        fatalError("Error in fetching records")
    }
}

Screenshot 在此处输入图片说明

Update: number of row

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultController.sections {
        return sections.count
    }
    return 0
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultController.sections {
        let currentSection = sections[section]
        return currentSection.numberOfObjects
    }
    return 0
}

I'm new in core data. I'm already fetch data from cart entity. My table view's looks like the screenshot. Look at Cart-user(38)-363690, it shows 2 cell in 1 cart Id because it has 2 photos. how to only show one cell even if it has 2 or more photos?

From this what I can Understand is if photos is there for cart it should show only one row and display the count of photos in the cell. For that the numberOfRowsInSection method should return only 1. No need to return number of images. and in cellForRowAtIndexPath method configure the row based on number of photos in the section.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     if let sections = fetchedResultController.sections {
        return sections.count
     }
     return 0
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
     let title: String
     if let sections = fetchedResultController.sections {
        let currentSection = sections[indexPath.section]
        title  = "\(currentSection.numberOfObjects) Photos"
     } 
     else {
        title  = "0 Photos"
     }
     //set the label title for photos

    return cell
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM