iphone - UI TableView 单元格在 swift 中使用 coredata 打开包含多个数据的新 View

标签 iphone swift uitableview core-data uiviewcontroller

作为 iOS 和 Swift 的初学者,我有一个项目必须有一个包含多个单元格的表格 View ,其中每个单元格都包含多种数据类型。即字符串、日期等,其中在一个 View Controller 中,有用于查看单元格的 TableView ,第二个 View Controller 用于创建单元格并输入数据,第三个 View 用于在单击细胞。我决定使用 coredata 来存储所有这些内容,因为我被告知这对于初学者来说最有效且最简单。我已经在这个问题上使用了几个教程,但没有一个可以处理我遇到的此类问题。最好的例子是联系人列表在 iOS 上的工作原理。 到目前为止我所做的代码是这样的:

 var titleCellList = [NSManagedObject]()
 var infoCellList = [NSManagedObject]()

class CellsViewController: UIViewController, UITableViewDataSource,    UITableViewDelegate {

@IBOutlet var cellsTableView: UITableView!

//MARK: Default Functions

override func viewDidLoad() {
    super.viewDidLoad()
    title = "\"Lists\""
    cellsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    // Do any additional setup after loading the view.
}

//标记:UITableViewDataSource

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return TitleCellList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
        let cellTitle = titleCellList[indexPath.row]
        cell.textLabel!.text = cellTitle.valueForKey("title") as? String

        return cell
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
    cellsTableView.reloadData()
}

//MARK:存储CoreData

 func saveName(name: String) {
    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let entity =  NSEntityDescription.entityForName("Data", inManagedObjectContext: managedContext)
    let title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)

    //3
    title.setValue(name, forKey: "title")

    //4
    var error: NSError?
    if !managedContext.save(&error) {
        println("Could not save \(error), \(error?.userInfo)")
    }
    //5
    titleCellList.append(title)
}

//MARK:获取CoreData

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let fetchRequest = NSFetchRequest(entityName:"Data")

    //3
    var error: NSError?
    let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

    if let results = fetchedResults {
        titleCellList = results
    } else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}

//MARK:表格编辑方法

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}


func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if editingStyle == UITableViewCellEditingStyle.Delete {

            let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let context:NSManagedObjectContext = appDel.managedObjectContext!
            context.deleteObject(titleCellList[indexPath.row] as NSManagedObject)
            titleCellList.removeAtIndex(indexPath.row)
            context.save(nil)

            cellsTableView.reloadData()
        }
    }

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        println("Row: \(row)")

        println(titleCellList[row])
        performSegueWithIdentifier("checkCellSegue", sender: self)
    }

第二个 View Controller (用于创建包含数据的单元格的 Controller )

class AddNewViewController: UIViewController, UITextFieldDelegate {


@IBOutlet var titleTextField: UITextField!
@IBOutlet var shortInfoTextView: UITextView!

//MARK: Default Functions

override func viewDidLoad() {
    super.viewDidLoad()
    self.titleTextField.delegate = self


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

@IBAction func addDataButtonPressed(sender: UIButton) {

    if titleTextField.text != ""  {
    CellsViewController().saveName(titleTextField.text)
    titleTextField.text = ""
    shortInfoTextView.text = ""
        println("New title Added!")
    }else {
        println("No empty titles allowed!")
    }
}

现在,大部分代码来自教程,当我尝试添加其他数据实体时,它不起作用。在数据模型中,我目前只有 1 个名为“Data”的实体,其中包含 4 个模型。因此,总而言之,我需要在一个实体中存储 4 个数据模型,并在单击单元格时将它们加载到不同的 View Controller 上,当然,该单元格具有用户编写的标题。需要注意的是,我花了几个小时在网上搜索答案,所以这是我的最后一行。

任何帮助将不胜感激。

最佳答案

所以,这是我在这个小问题上使用的一种方法。我基本上只是使用prepareForSegue 方法传递参数,并在其中传递我想要在其他类/VC 中使用的数据。

代码:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    // Setter for Second VC, destination path --> var declarations in Second VC

    if segue.identifier == "checkCellSegue" {
        let destination = segue.destinationViewController as! SecondViewController
        if let indexPath = self.tableView?.indexPathForCell(sender as! UITableViewCell) {
            let object = fetchedResultsController?.objectAtIndexPath(indexPath) as? Data
            destination.cellTitle = object?.cellTitle
            destination.textViewInfo = object?.textViewInfo
            destination.timerValue = object?.timerValue

        }
    }  

因此,首先我们声明目的地,即我们的第二个 VC 的名称或您命名的任何名称。然后,由于我是通过 TableView 单元访问数据,所以我们需要使用 indexPath 获取我的 CoreData 实体。之后,最终声明是模型类,其中包含来自实体的所有数据值,它将像单例一样工作。

destination.cellTitle // --> in the 2.nd VC we declared a new var called cellTitle, var cellTitle:String

object?.cellTitle  // --> in the model class "Data.swift" the declaration is @NSManaged var cellTitle:String

所以,就是这样。我对 iOS 还是个小新手,所以如果有任何错误,请指出。

关于iphone - UI TableView 单元格在 swift 中使用 coredata 打开包含多个数据的新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32433908/

相关文章:

ios - [__NSCFString 计数] : unrecognized selector sent to instance

iphone - 如何在 Spotify iOS 应用程序中模仿可调整大小的 StatusBar

iPhone : Custom tabbar without the awful More menu

ios - CloudKit Query 适用于 Xcode 发布版本,不适用于 TestFlight

ios - danielgindi/iOSCharts 库 : x axis label in horizontal bar chart

ios - UIActivityIndi​​cator 随 tableView 滚动

iPhone:核心位置弹出问题

iPhone iOS 如何使 UIRotationGestureRecognizer 和 UIPinchGestureRecognizer 协同工作以缩放和旋转带有 subview 的 UIView?

swift - 未调用委托(delegate)方法

ios - UITableView左右填充