Проблема удаления основной записи данных путем выбора строки в табличном представлении - PullRequest
1 голос
/ 24 января 2012

Использование основных данных для заполнения моего табличного представления. Я не понимаю, как удалить одну запись из основных данных.

Я использую uitableview, а не контроллер.

Вот код, который я использую:

-(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.view.tag = indexPath.row;
    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;
}

VehicleListCell* cell = (VehicleListCell *)[recognizer view];

cellValueForLongPress = cell.licPlate.text;

NSLog(@"cell value: %@", cellValueForLongPress);

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ;
alert.tag = recognizer.view.tag;
[alert addButtonWithTitle:@"Remove from Favourites"];
[alert addButtonWithTitle:@"Take to Map"];

[alert show];}

здесь, в методе просмотра предупреждений, выбранная строка будет удалена (если ([title isEqualToString: @ "Удалить из избранного"])):

-(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);
///////// to remove the object from core data
    [licensePlateArray removeObjectAtIndex:alert.tag];

}
else if([title isEqualToString:@"Take to Map"])
{
    NSLog(@"Go to MapView");
}

NSError *error;

if (![context save:&error]) {
    NSLog(@"Error Occured");
}
[favouritesTable reloadData];}

1 Ответ

1 голос
/ 24 января 2012

Запишите это в cellForRowAtIndexPath

    UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)];
    pressRecongnizer.view.tag = indexPath.row;
    pressRecongnizer.minimumPressDuration = 0.5f;
    [cell addGestureRecognizer:pressRecongnizer];
    [pressRecongnizer release];

и используйте alertview вот так

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ;
alert.tag = recognizer.view.tag;
[alert addButtonWithTitle:@"Remove from Favourites"];
[alert addButtonWithTitle:@"Take to Map"];    
[alert show];

затем напишите это в -(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex

[YourArray removeObjectAtIndex:alert.tag];    
[YourTable reloadData];

Пожалуйста, используйте этот код в соответствующем месте в вашем коде ..

Счастливое кодирование ..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...