使用核心数据填充我的表格视图。我没有得到的是如何从核心数据中删除单个条目。
以下是我正在使用的代码:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == favouritesTable) {
cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
cellValue = [filteredListItems objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = @"vlCell";
VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(@"Cell Created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"VehicleListCell" owner:nil options:nil];
for (id currentObject in nibObjects) {
if ([currentObject isKindOfClass:[VehicleListCell class]]) {
cell = (VehicleListCell *)currentObject;
}
}
UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)];
pressRecongnizer.minimumPressDuration = 0.5f;
[cell addGestureRecognizer:pressRecongnizer];
[pressRecongnizer release];
}
cell.textLabel.font = [UIFont systemFontOfSize:10];
Favouritesdata *favdata = [licensePlateArray objectAtIndex:indexPath.row];
[[cell ignition] setImage:[UIImage imageNamed:@"ignition.png"]];
[[cell direction] setImage:[UIImage imageNamed:@"south.png"]];
cell.licPlate.text = [favdata licenseplate];
NSLog(@"cellvalue for cellforRow: %@", cell.licPlate.text);
return cell;}
在UILongPressGestureRecognizer的方法中:
- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ;
[alert addButtonWithTitle:@"Remove from Favourites"];
[alert addButtonWithTitle:@"Take to Map"];
[alert show];}
在警报视图方法中:
-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *title = [alert buttonTitleAtIndex:buttonIndex];
NSManagedObjectContext *contextFav = [app managedObjectContext];
Favouritesdata * favourites = [NSEntityDescription insertNewObjectForEntityForName:@"Favouritesdata" inManagedObjectContext:contextFav];
if([title isEqualToString:@"Remove from Favourites"])
{
NSLog(@"cellValueForLongPress: %@", cellValueForLongPress);
if (cellValueForLongPress <= 0) {
NSLog(@"No data to delete");
}
else {
favourites.licenseplate = cellValueForLongPress;
}
[alert dismissWithClickedButtonIndex:0 animated:YES];
}
else if([title isEqualToString:@"Take to Map"])
{
NSLog(@"Go to MapView");
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Error Occured");
}}
答案 0 :(得分:1)
如果要从CoreData存储中删除托管对象,则应该:
NSManagedObjectContext
,您将删除对象:context
NSManagedObject
的引用:object
然后删除对象非常简单:
[context deleteObject:object];
你应该知道
i
。 NSObject *object = [licensePlateArray objectAtIndex:i];
答案 1 :(得分:0)
您必须识别NSManagedObject,然后在managedObjectContext上调用 deleteObject 。然后,此对象将从核心数据中删除。
但是你必须提供一种机制来“以某种方式”获取特定tableview行后面的对象。