使用Core Data - Swift将日期添加为节标题标题

时间:2016-05-17 00:37:06

标签: ios swift uitableview core-data

我尝试以Month,Year的形式添加创建新单元格的日期作为Sections标题标题。下面我有我的所有核心数据代码,但似乎得到了错误

"无法将string类型的值转换为预期的参数类型nsdate" 和 "使用未解析的标识符date"

Core Data Model Screenshot

核心数据管理器 - PRManager.swift

import UIKit

var taskMgr: TaskManager = TaskManager()

struct AddPR {
    var name = "Name"
    var desc = "Description"
    var weight = "Weight"
    var date = "Date"
}

class TaskManager: NSObject {

var tasks = [AddPR]()
var persistenceHelper: PersistenceHelper = PersistenceHelper()

override init(){

    let tempTasks:NSArray = persistenceHelper.list("Task")
    for res:AnyObject in tempTasks{
        tasks.append(AddPR(name:res.valueForKey("name")as! String,desc:res.valueForKey("desc") as! String,weight:res.valueForKey("weight") as! String,date:res.valueForKey("date")as! String))
    }
}


func addTask(name:String, desc: String, weight: String){

    var dicTask: Dictionary<String, String> = Dictionary<String,String>()
    dicTask["name"] = name
    dicTask["desc"] = desc
    dicTask["Weight"] = weight
    **dicTask["Date"] = date**


    if(persistenceHelper.save("Task", parameters: dicTask)){
        **tasks.append(AddPR(name: name, desc: desc, weight: weight, date: date))**
    }
}

func removeTask(index:Int){

    let value:String = tasks[index].name

    if(persistenceHelper.remove("Task", key: "name", value: value)){
        tasks.removeAtIndex(index)
    }
}
}

PersistenceHelper.swift

import UIKit
import CoreData

class PersistenceHelper: NSObject {

var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext;

override init(){
    context = appDel.managedObjectContext
}

func save(entity: String, parameters: Dictionary<String,String> )->Bool{

    let newEntity = NSEntityDescription.insertNewObjectForEntityForName(entity, inManagedObjectContext: context)
    for (key, value) in parameters{
        newEntity.setValue(value, forKey: key)
    }

    do {
        try context.save()
        return true
    } catch _ {
        return false
    }
}

func list(entity: String ) ->NSArray{

    let request = NSFetchRequest(entityName: entity)
    request.returnsObjectsAsFaults = false;
    let results: NSArray = try! context.executeFetchRequest(request)
    return results
}

func remove(entity:String, key:String, value:String)->Bool{

    let request = NSFetchRequest(entityName: entity)
    request.returnsObjectsAsFaults = false
    request.predicate = NSPredicate(format: "\(key) = %@", value)
    let results: NSArray = try! context.executeFetchRequest(request)

    if(results.count>0){

        let res = results[0] as! NSManagedObject
        context.deleteObject(res)
        do {
            try context.save()
        } catch _ {
        }
        return true
    }

    return false
}
}

查看控制器

import UIKit


class PRViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tblTasks : UITableView!

//For persisting data
let defaults = NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {
    super.viewDidLoad()
    self.tblTasks.reloadData()
    tblTasks.registerNib(UINib(nibName: "PRTableViewCell", bundle: nil), forCellReuseIdentifier: "PRTableCell")
    tblTasks.tableFooterView = UIView()

}

override func viewWillAppear(animated: Bool) {
    self.tblTasks.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


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



    return 1

}


func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    let formatter = NSDateFormatter() // This is slightly inefficient for a large number of rows because setting up NSDateFormatter is expensive. You could make this a property.
    formatter.dateStyle = .ShortStyle
    formatter.timeStyle = .NoStyle

    let sectionHeaderDate = taskMgr.tasks[section].date

这是我得到的无法将string类型的值转换为期望的参数类型nsdate错误

的地方
    **let dateCreated = formatter.stringFromDate(sectionHeaderDate)**
    return dateCreated
}

//Define how our cells look - 2 lines a heading and a subtitle
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let identifier = "PRTableCell"
    var cell: PRTableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? PRTableViewCell

    if cell == nil {
        tableView.registerNib(UINib(nibName: "PRTableViewCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? PRTableViewCell
    }


//        Assign the contents of our var "items" to the textLabel of each cell
//        cell.textLabel!.text = taskMgr.tasks[indexPath.row].name
//        cell.detailTextLabel!.text = taskMgr.tasks[indexPath.row].desc

    cell.PRLabel.text = taskMgr.tasks[indexPath.row].name
    cell.NotesLabel.text = taskMgr.tasks[indexPath.row].desc
    cell.WeightLabel.text = taskMgr.tasks[indexPath.row].weight + "lb"






    return cell



}

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

    if (editingStyle == UITableViewCellEditingStyle.Delete){

        taskMgr.removeTask(indexPath.row)
        tblTasks.reloadData()
    }


    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        let numberOfSections = taskMgr.tasks.count
        return numberOfSections
    }





}
}

AddCell.swift

import UIKit

class addPRTableViewController: UITableViewController, UITextFieldDelegate {

@IBOutlet var txtPR: UITextField!
@IBOutlet var txtDesc: UITextField!

@IBOutlet weak var txtWeight: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
    txtPR.delegate = self


}



// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    // #warning Incomplete implementation, return the number of sections

    return 1
}

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

    // #warning Incomplete implementation, return the number of rows

    return 5
}


func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
               replacementString string: String) -> Bool
{
    let maxLength = 25
    let currentString: NSString = textField.text!
    let newString: NSString =
        currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}



//    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        
//        let cell = tableView.dequeueReusableCellWithIdentifier("prcell", forIndexPath: indexPath)
//        
//        
//        // Configure the cell...
//        
//        
//        
//        return cell
//    }

//Button Clicked
@IBAction func btnAddTask(sender : UIBarButtonItem){
    if (txtPR.text == ""){
        //Task Title is blank, do not add a record
    } else {
        //add record
        let name: String = txtPR.text!
        let description: String = txtDesc.text!
        let weight: String = txtWeight.text!
        taskMgr.addTask(name, desc: description, weight: weight)

        //dismiss keyboard and reset fields

        self.view.endEditing(true)
        txtPR.text = nil
        txtDesc.text = nil
        txtWeight.text = nil


    }
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}


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

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
    header.textLabel!.textColor = UIColor(red: 246/255, green: 75/255, blue: 55/255, alpha: 1.0)  //make the text white
}

0 个答案:

没有答案