iOS,Swift,核心数据+多个表 [英] ios, swift, core data + multiple tables

查看:59
本文介绍了iOS,Swift,核心数据+多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ios和swift非常陌生。在单个视图上,如何将两个不同的提取请求发送到两个不同的表视图?我有一个类级别的fetchReq函数,该函数使用NSPredicate接受参数并为我提供所需的各种结果。 tablView函数是唯一知道哪个表是哪个表的地方,但是看起来好像是要在viewDidLoad上立即决定要加载哪些数据的决定。可以帮助我重组核心数据代码,以便为每个表获取不同的获取请求吗?

I'm very new to ios and swift. On a single view, how can I send two different fetch requests to two different table views? I have a class level fetchReq function that uses NSPredicate to take a parameter and give me the varied results that I want. The only place that knows which table is which is the tablView func, but it looks like the decision about which data to load gets made immediately on viewDidLoad. Could some kind soul help me restructure the core data code so that I get a different fetch request for each table?

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,每个表都有两个不同的提取请求。如果您的表委托和数据源都是该视图控制器,则需要切换并提供相应的内容...例如:

You need 2 fetchedResultsControllers with the two different fetch requests for each table. If your tables delegates and datasources are both this view controller, you'll need to switch and provide the corresponding content... for example:

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

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

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

Another option would be to create 2 custom MYTableViewDataSource objects and set the datasource for each table view to that... It might make it more obvious when you've got unexpected behaviour and make the data easier to control.

这篇关于iOS,Swift,核心数据+多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆