我已经使用coredata在表视图中存储名称。我已经对行进行了排序并且正在运行。问题是当我在表视图中添加一行时,该行被添加并进行了排序。但是新行未与旧行进行排序。这是我的代码。



import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource {


@IBOutlet weak var tableView: UITableView!

var people = [NSManagedObject]()

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    title = "Hit List"
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "Person")
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        people = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

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

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

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

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
    let person = people[indexPath.row]
    cell?.textLabel?.text = person.valueForKey("name") as? String
    return cell!
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    let context = appDelegate.managedObjectContext
    context.deleteObject(people[indexPath.row] as NSManagedObject)
    people.removeAtIndex(indexPath.row)
    do {
        try context.save()
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
    //tableView.reloadData()
    // remove the deleted item from the `UITableView`
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}

@IBAction func addName(sender: AnyObject) {

    let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .Alert)
    let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in
        let textField = alert.textFields?.first
        self.saveName(textField!.text!)
        self.tableView.reloadData()
    })

    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction) -> Void in
    }

    alert.addTextFieldWithConfigurationHandler {
        (textField: UITextField) -> Void in
    }

    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    presentViewController(alert,
        animated: true,
        completion: nil)
}

func saveName(name: String) {

    let managedContext = appDelegate.managedObjectContext
    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
    let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
    person.setValue(name, forKey: "name")
    do {
        try managedContext.save()
        people.append(person)
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}
}

最佳答案

该数组未排序,因为新人员仅附加到

您有四个选择:


追加人员,将people排序到位。

do {
  try managedContext.save()
    people.append(person)
    people.sortInPlace { ($0.valueForKey("name") as! String) < ($1.valueForKey("name") as! String) }
    self.tableView.reloadData()
} catch let error as NSError  {
   print("Could not save \(error), \(error.userInfo)")
}

不要追加人员,通过people重新获取数据(如NSFetchRequest中一样)
使用viewWillAppear算法在适当的索引处将人插入people
使用orderedInsert及其委托方法(有许多教程介绍如何做到这一点)。


在四个选项中的每个选项之后,重新加载表格视图。

关于ios - 使用coredata对tableview行进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33871249/

10-14 20:52
查看更多