【发布时间】:2015-08-20 22:46:18
【问题描述】:
我在单独的视图中有两个表,每个表的列表在 CoreData 中都有一个单独的实体。用户可以点击任何单元格中的按钮将其移动到另一个列表。这很有效,只需点击一下即可移动项目,所有内容都会在应用关闭后保存并持续存在。
问题
目前,代码应该计算目标列表中的项目,然后将要移动的项目附加到其新列表的末尾。这不会发生。相反,该项目是随机插入的(不是在末尾或开头)。但是,一旦它被插入,任何进一步的移动项目都将直接位于它的下方。我尝试用 1 替换 count 函数,因为我真的希望移动的项目无论如何都显示在顶部,但这无济于事。
代码
首先,这是每次主视图出现时运行加载主列表的 viewDidLoad 代码:
override func viewDidLoad() {
super.viewDidLoad()
currentListEntity = curList
//Load the list from Core Data
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: currentListEntity)
let sortDescriptor = NSSortDescriptor(key: "displayOrder", ascending: true )
fetchRequest.sortDescriptors = [ sortDescriptor ]
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]
if let results = fetchedResults {
taskList_Cntxt = results
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
我希望将移动的对象附加到新列表的末尾(这是实体参数)的功能,而是将其插入到其他列表项中:
func addToList (sender: AnyObject, entity: String) {
//Setup CoreData context
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName(entity, inManagedObjectContext: managedContext)
let task = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
//Figure out the cell pressed
let button = sender as! UIButton
let contentView = button.superview!
let cell = contentView.superview as! CustomTableViewCell_F2
//Set cell contents to variables
var nameValue = cell.nameLabel!.text
var descValue = cell.descLabel!.text
//Set content variables to NSObject called "task"
task.setValue(nameValue, forKey: "name")
task.setValue(descValue, forKey: "desc")
//Error check
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//Get count, append to end, sort, save
var insertAt = taskList_Cntxt.count
addTask(task, displayOrder: insertAt)
updateDisplayOrder()
managedContext.save(nil)
}
//Referenced by larger add-task function
func addTask( task: NSManagedObject, displayOrder: Int ) {
taskList_Cntxt.insert( task, atIndex: displayOrder )
updateDisplayOrder()
}
//Called to update Core Data after append, delete, and drag/drop
func updateDisplayOrder() {
for i in 0..<taskList_Cntxt.count {
let task = taskList_Cntxt[i]
task.setValue( i, forKey: "displayOrder" )
}
}
关于如何解决这个问题的任何想法?理想情况下附加到列表的顶部,但此时将其附加到底部也很好。
【问题讨论】:
-
您似乎正在将任务添加到您的函数
addTask中的列表中,而您没有包括该列表。另外updateDisplayOrder听起来肯定会影响显示顺序,但也不包括在内。几乎可以肯定,这两者对于正确订购都至关重要。 -
@TomHarrington 很抱歉,在熬夜后发布了这篇文章,试图解决这个问题和另一个问题,显然需要睡觉!我已经包含了这两个函数
标签: swift core-data nsmanagedobjectcontext nssortdescriptor