【问题标题】:custom fetch core data (swift)自定义获取核心数据(swift)
【发布时间】:2016-05-12 03:55:13
【问题描述】:

我的数据模型

获取函数

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")
    }
}

截图

更新:行数

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
}

我是核心数据的新手。我已经从购物车实体获取数据。我的表格视图看起来像屏幕截图。查看 Cart-user(38)-363690,它在 1 个购物车 ID 中显示 2 个单元格,因为它有 2 张照片。即使有 2 张或更多照片,如何只显示一个单元格?

【问题讨论】:

  • 问题可能与 numberofsections 和 numberofrowsinsection 方法有关。请在此处添加该方法
  • 好的,请检查我编辑的问题@Johnykutty
  • Cart-user(38)-XXXXX 是表格视图单元格或其部分标题的一部分?
  • 我认为这是部分标题,所以对你来说,如果照片在那里,它应该只显示一行并显示那里的照片数量正确吗?
  • 部分,实际上我只使用部分来显示 1 个购物车 ID 中有多少单元格。我只想为每个 cartId 显示 1 个单元格。 @Johnykutty

标签: ios swift core-data nsfetchedresultscontroller datamodel


【解决方案1】:

据此,我可以理解的是,如果购物车中有照片,它应该只显示一行并显示单元格中的照片数。为此,numberOfRowsInSection 方法应仅返回 1。无需返回图像数量。并在cellForRowAtIndexPath 方法中根据部分中的照片数量配置行。

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
}

【讨论】:

  • 嘿,谢谢你的回答。它有效,但有什么方法可以在不更改部分的情况下做到这一点?我的意思是我只使用 section 来指导我,并计划稍后隐藏 sectionTile。
  • 我无法完全了解您的需求。所以这是我根据我的理解保证的方法
猜你喜欢
  • 2017-12-15
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多