ios,swift,核心数据+多表

标签 ios core-data swift

我是 ios 和 swift 的新手。在单个 View 中,如何向两个不同的 TableView 发送两个不同的提取请求?我有一个类级别的 fetchReq 函数,它使用 NSPredicate 获取一个参数并为我提供我想要的各种结果。唯一知道哪个表是哪个表的地方是 tablView 函数,但看起来加载哪些数据的决定是在 viewDidLoad 上立即做出的。有没有好心人能帮我重构核心数据代码,让我对每个表都有不同的获取请求?

import UIKit
import CoreData

class CustomTableViewCell : UITableViewCell {
    @IBOutlet var l1: UILabel?
    @IBOutlet var l2: UILabel?

    func loadItem(#number: String, name: String) {
        l1!.text = number
        l2!.text = name
    }
}

class ViewController: UIViewController, UITableViewDelegate, NSFetchedResultsControllerDelegate, UITableViewDataSource {

    @IBOutlet var tableView1: UITableView!
    //this is my second table - Ive connected it in the IB to this VC. both tables work, but are identical
    @IBOutlet var tableView2: UITableView!
    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
    var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()


    //the filtering happens inside this function. it gets called via didLoad, not cellsForRows
    func playerFetchRequest(playerType: String) -> NSFetchRequest {
        let fetchRequest = NSFetchRequest(entityName: "Players")
        let sortDescriptor = NSSortDescriptor(key: "number", ascending: true)
        let filter = NSPredicate(format: "%K = %@", "type", playerType)
        fetchRequest.sortDescriptors = [sortDescriptor]
        fetchRequest.predicate = filter
        return fetchRequest
    }

    func getFetchedResultController() -> NSFetchedResultsController {
        fetchedResultController = NSFetchedResultsController(fetchRequest: playerFetchRequest(playerType), managedObjectContext:managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
        return fetchedResultController
    }

    //remember: to create a table with multiple sections just implement the numberOfSectionsInTableView(_:) method
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
        {return numberOfRowsInSection} else {return 0}
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if (tableView == tableView2) {
        var playerType = "Forward"
        var cell:CustomTableViewCell = self.tableView1.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
        let player = fetchedResultController.objectAtIndexPath(indexPath) as DataModel
        cell.l2?.text = player.lastName + ", " + player.firstName
        cell.l1?.text = player.number
        println(tableView)
        return cell
        }
        else {
            var playerType = "Defender"
            var cell:CustomTableViewCell = self.tableView2.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
            let player = fetchedResultController.objectAtIndexPath(indexPath) as DataModel
            cell.l2?.text = player.lastName + ", " + player.firstName
            cell.l1?.text = player.number
            println(tableView)
            return cell
        }
    }

    func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        println("You selected cell #\(indexPath.row)!")
    }

    override func viewDidLoad() {
        var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
        tableView1.registerNib(nib, forCellReuseIdentifier: "customCell")
        tableView2.registerNib(nib, forCellReuseIdentifier: "customCell")
        fetchedResultController = getFetchedResultController()
        fetchedResultController.delegate = self
        fetchedResultController.performFetch(nil)
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func controllerDidChangeContent(controller: NSFetchedResultsController!) {
        tableView1.reloadData()
        tableView2.reloadData()
    }
}

最佳答案

您需要 2 个 fetchedResultsControllers,每个表有两个不同的提取请求。如果你的表委托(delegate)和数据源都是这个 View Controller ,你需要切换并提供相应的内容......例如:

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

    if (tableView == tableView2)
    {
        return fetchedResultController2.sections?[section].numberOfObjects
    }
    else
    {
        return fetchedResultController.sections?[section].numberOfObjects
    }
}

另一种选择是创建 2 个自定义 MYTableViewDataSource 对象并将每个 TableView 的数据源设置为...当您遇到意外行为并使数据更易于控制时,它可能会更加明显。

关于ios,swift,核心数据+多表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26461219/

相关文章:

ios - 如何知道 ios 中另一个 View 类中一个 View Controller 的 ImageView 的 x、y 坐标和宽度、高度?

objective-c - 为什么使用 NSDate 将 double 转换为字符串会额外增加 30 分钟

iphone - 核心数据一对多关系

ios - 为什么我的 NSFetchedResultsController 加载所有行?

swift - 快速更新标签中的 slider 值

swift - 如何在自定义表格 View 单元格中创建自定义 View ?

ios - HStack 中的两个按钮相互执行操作

iphone - 如何从开发人员 iPhone 上的开发人员应用程序检索 Core Data SQL 存储

ios - 减少 SKAction 循环中的 waitForDelay

ios - 界面 View : frame size different of bounds size?