如何在表视图控制器中从 Realm 数据库中删除对象

3
如果这是我的代码,为什么我在使用realm存取数据时会出现错误:Value of type 'RLMResults' has no member 'arraySortedByProperty'。
var items = [NSManagedObject]()

var todos: RLMResults {
    get {
        return ToDoItem.allObjects()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    title = "Todos"

}


func deleteRowAtIndexPath(indexPath: NSIndexPath)
{
    let realm = RLMRealm.defaultRealm() //1
    let objectToDelete = todos[UInt(indexPath.row)] as! ToDoItem //2
    realm.beginWriteTransaction() //3
    realm.deleteObject(objectToDelete) //4
    realm.commitWriteTransaction() //5

     todos = ToDoItem.allObjects().arraySortedByProperty("name", ascending: true) //6

    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) //7
}
3个回答

3

我认为您不需要这行代码:

todos = ToDoItem.allObjects().arraySortedByProperty("name", ascending: true) //6

如果您想从Realm数据库中删除任何对象,只需删除该行即可,您的代码将如下所示:
func deleteRowAtIndexPath(indexPath: NSIndexPath)
{
    let realm = RLMRealm.defaultRealm() //1
    let objectToDelete = todos[UInt(indexPath.row)] as! ToDoItem //2
    realm.beginWriteTransaction() //3
    realm.deleteObject(objectToDelete) //4
    realm.commitWriteTransaction() //5
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) //7
}

你可以这样调用这个方法:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        deleteRowAtIndexPath(indexPath)
    }
}

我尝试使用上述代码删除行,但应用程序崩溃并显示“终止应用程序,原因:未捕获的异常 'RLMException',原因:无效的数组类型 - 容器必须是 RLMArray、RLMResults 或包含 RLMObjects 的 NSArray”。 - amisha.beladiya
错误本身就已经解释了一切.. :) - Dharmesh Kheni

0

arraySortedByProperty:ascending:Realm Objective-C 0.87 版本中更名为 sortedResultsUsingProperty:ascending:


但是在删除单元格后,我的程序会崩溃。 - Ashwini

0

todos 属性是只读属性,因此您无法将其分配给任何值。另外,您需要在 allObjects() 返回的任何类型上实现自己的 'arraySortedByProperty' 或只需调用 sort()。

var todos: RLMResults {
    get {
        return ToDoItem.allObjects()
    }
    set { todos = newValue }
}

//assuming return value of allObjects has a property called name 
todos = ToDoItem.allObjects().sort { $0.name < $1.name } 

RLMResults不是一个数组吗?如果不是,它是什么? - Lukas
按下alt键并单击RLMResults以查找它是什么。我假设它是一个数组,因为allObjects听起来像是在集合上调用的某些东西。 - Lukas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接