简体   繁体   English

从TableView和数据库中删除单元格

[英]Deleting a Cell from TableView and from Database

I'm building a Browser, and I have a database where the bookmarks of my browser are stored. 我正在构建一个浏览器,并且有一个存储浏览器书签的数据库。

In my table "Bookmarks" I have an "ID (AUTOINCREMENT)" and a "URL" field. 在我的表格“书签”中,我有一个“ ID(AUTOINCREMENT)”和一个“ URL”字段。 The thing is, when I delete an arbitrary ID there remains a hole in my database. 问题是,当我删除任意ID时,数据库中仍然存在漏洞。 Like "ID1, ID2, ID700"... and when I go and list this in a TableView, these are skipped. 就像“ ID1,ID2,ID700”一样...当我在TableView中列出它时,这些内容将被跳过。

So, row number 1, isn't necessary the ID number 1. 因此,行号1不需要ID号1。

How can I manage to delete a row in my TableView, and delete the corresponding field (ID and URL) from my Database at the same time? 如何在TableView中删除一行,并同时从数据库中删除相应的字段(ID和URL)?

Here is a piece of my code: 这是我的一段代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//CRIA A CELULA DESTA LINHA DA TABELA
static NSString * CellIdentifier = @"Cell";
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    //FAZ CACHE DA CELULA PARA EVITAR CRIAR MUITOS OBJETOS DESNECESSARIOS DURANTE O SCROLL
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

//RECUPERA O NUMERO DA LINHA 0, 1, 2, 3...
NSInteger row = indexPath.row;

self.counter = 1;

NSString * bookmark = [[Dados sharedDB]getBookmark:row+1];

//TEXT
if ([bookmark isEqualToString:@"ERROR"]) {

    do {
        self.counter++;
        bookmark = [[Dados sharedDB]getBookmark:row+self.counter];
    } while ([bookmark isEqualToString:@"ERROR"]);
}

cell.textLabel.text = [NSString stringWithFormat:@"%@", bookmark];

return cell;

} }

You have to first delete the data in database and then fetch the modified(new) data from database and reload the tableview. 您必须首先删除数据库中的数据,然后从数据库中获取已修改的(新)数据并重新加载表视图。

So how it works is, you have to make use of didSelectRowAtIndexPath method to know which row has been selected. 因此,它是如何工作的,您必须使用didSelectRowAtIndexPath方法来知道已选择了哪一行。 Using indexPath.row property, determine the ID of that entry ( I believe you must have fetched all the data in an array before displaying). 使用indexPath.row属性,确定indexPath.row目的ID(我相信您必须在显示之前已获取数组中的所有数据)。 Then, in database, delete that particular entry. 然后,在数据库中,删除该特定条目。 Assuming, you are using core data, you will have to fetch that entry, delete it and then save it in managed object context. 假设您正在使用核心数据,则必须获取该条目,将其删除,然后将其保存在托管对象上下文中。 After this is done, fetch all the data and store it in the array of your view controller. 完成此操作后,获取所有数据并将其存储在视图控制器的数组中。 Last, call the method of [self.tableview reloadData] . 最后,调用[self.tableview reloadData]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM